0

Django菜鸟问题:

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

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 管理类以允许管理站点用户从其“图像”集合中选择和图像?

4

1 回答 1

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 张图片

于 2013-09-14T19:03:56.853 回答