Django模型 - 如何从集合中的实例创建selected_instance字段

时间:2013-09-14 18:34:21

标签: django-models

Django noob问题:

我想创建一个允许用户分享汽车信息的网站。每辆车都应该有一组图像,并且提交者应该选择一个用于在列表页面上表示汽车的图像。一组基本模型如下所示:

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类中放置了“selected”BooleanField?如何配置Car和CarImage管理类以允许管理站点用户从其“图像”集合中为汽车选择和映像?

1 个答案:

答案 0 :(得分:0)

首先,我建议您使用辅助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',)

因此,您可以在项目中使用此类,对其进行子类化。 一个简单的问题解决方案是将您的图片库附加到您的汽车,并创建一个属性,该属性是一个IntegerField,用于存储图片库中的图片位置:

...

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()

所以,如果selected_picture是n,你只需要在image_gallery里面得到第n张图片