【问题标题】:Django - count numbers of same field in a modelDjango - 计算模型中相同字段的数量
【发布时间】:2020-05-19 22:55:55
【问题描述】:

我是 Django 新手,我正在构建一个电子商务网站 (db: sqlite3)。每件特价商品都有 1-5 张图片上传。所以我在这里找到了模型:

class Item(models.Model):
    '''Item model with maximum 5 images uploaded'''

    <--snip-->

    image_1 = models.ImageField(upload_to='items/')
    image_2 = models.ImageField(upload_to='items/', blank=True)
    image_3 = models.ImageField(upload_to='items/', blank=True)
    image_4 = models.ImageField(upload_to='items/', blank=True)
    image_5 = models.ImageField(upload_to='items/', blank=True)

为了为每个项目创建一个 carousel (bootstrap4),我需要知道上传了多少张图片。我的想法是在类中创建一个函数来找出这个模型中有多少ImageField,有多少不是空白的。

所以我的问题是:
1.有没有更好的方式来创建ImageField,更动态的方式?
2. 是否可以找出一个模型中非空白的相同字段的数量?

【问题讨论】:

  • Item 模型是否也只有图像字段或其他字段?
  • 是的,还有很多其他字段

标签: django model django-queryset imagefield


【解决方案1】:

我将为图像创建一个单独的模型并将其链接到 Item 模型。这将使过滤更容易,并使图像上传更灵活。

class ItemImage(models.Model):
    item = models.ForeignKey(Item)
    image = models.ImageField(upload_to='items/')

class Item(models.Model):
    <--snip-->

    # we add a model property then do a reverse lookup in order to 
    # count images linked to the item object
    # this can then be accessed by item_obj.image_count
    @property
    def get_image_count(self)
        return self.itemimage_set.all().count()

【讨论】:

  • 这也出现在我的脑海中,但我认为使用 django admin 在单个页面上的一个会话中创建一个项目要容易得多...
  • 您可以使用TabularInline django 类来轻松/动态地在同一页面上添加更多图像。你可以阅读更多关于这个here
猜你喜欢
  • 2019-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-06
  • 2017-11-07
  • 1970-01-01
  • 2018-10-11
  • 2021-11-14
相关资源
最近更新 更多