Django models Django models-如何从集合中的实例创建选定的_实例字段
Django noob问题: 我想创建一个网站,允许用户分享有关汽车的信息。每辆车都应该有一组图像,提交者应该选择其中一个图像,用于在列表页面上表示该车。一组基本模型如下所示:Django models Django models-如何从集合中的实例创建选定的_实例字段,django-models,Django Models,Django noob问题: 我想创建一个网站,允许用户分享有关汽车的信息。每辆车都应该有一组图像,提交者应该选择其中一个图像,用于在列表页面上表示该车。一组基本模型如下所示: class Manufacturer(models.Model): name = models.CharField(max_length=255) class ModelBrand(models.Model): name = models.CharField(max_length=255) cl
class Manufacturer(models.Model):
name = models.CharField(max_length=255)
class ModelBrand(models.Model):
name = models.CharField(max_length=255)
class Car(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
# identifying information
manufacturer = models.ForeignKey(Manufacturer)
model_brand = models.ForeignKey(ModelBrand)
model_year = models.PositiveIntegerField()
class CarImage(models.Model):
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
car = models.ForeignKey(Car, related_name='images')
source_url = models.CharField(max_length=255, blank=True)
image = ImageField(upload_to='cars')
但是如何对所选图像进行建模?我是否在CarImage类中设置了“选定”布尔字段?如何配置Car和CarImage管理类,以允许管理站点用户从其“图像”集合中为汽车选择和设置图像?首先,我建议您使用辅助TimeStampedClass重构您的类
class TimeStampedModel(models.Model):
"""
Abstract class model that saves timestamp of creation and updating of a model.
Each model used in the project has to subclass this class.
"""
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now=True, editable=False)
class Meta:
abstract = True
ordering = ('-created_on',)
所以你可以在你的项目上使用这个类,对它进行子类化。
解决问题的一个简单方法是将图像库连接到汽车,并创建一个属性,该属性是一个整型字段,用于在图像库中存储图片位置:
...
class CarImage(TimeStampedField):
source_url = models.CharField(max_length=255, blank=True)
image = ImageField(upload_to='cars')
class Car(TimeStampedModel):
image_gallery = models.ManyToManyField(CarImage)
selected_picture = models.IntegerField(default=0)
# identifying information
manufacturer = models.ForeignKey(Manufacturer)
model_brand = models.ForeignKey(ModelBrand)
model_year = models.PositiveIntegerField()
所以,如果选中的图片是n,您只需要在图像库中获得第n张图片