有没有办法从模型中获取并显示用户发布的每个广告的图像数量

我正在尝试获取用户发布的每个广告的图像总数。我想在我的模板上显示这个计数。我在网上尝试了几种解决方案,看看我是否可以让它工作,但我有点碰壁了。这是我在电子商务网站上看到的;所以我知道这是可能的。请帮忙...


My Model


class Advert(models.Model):

    """All adverts"""


    STATUS_CHOICES = (

        ('draft', 'Draft'),

        ('published', 'Published')

    )


    title = models.CharField(max_length=49)

    description = models.TextField()

    price = models.PositiveIntegerField()

    date_created = models.DateTimeField(auto_now_add=True)

    date_posted = models.DateTimeField(auto_now=True)

    state = models.ForeignKey(State, on_delete=models.DO_NOTHING)

    city = models.CharField(max_length=255, blank=True, null=True)

    author = models.ForeignKey(User, on_delete=models.CASCADE)

    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)


    status = models.CharField(

        max_length=10, choices=STATUS_CHOICES, default='draft')

    image_primary = models.ImageField(

        upload_to="product_pictures", verbose_name='Image (required)')

    image_2 = models.ImageField(

        upload_to="product_pictures", blank=True, null=True)

    image_3 = models.ImageField(

        upload_to="product_pictures", blank=True, null=True)

    image_4 = models.ImageField(

        upload_to="product_pictures", blank=True, null=True)

    image_5 = models.ImageField(

        upload_to="product_pictures", blank=True, null=True, default=None)


    class Meta:

        ordering = ['-id']


    def __str__(self):

        return self.title

my View


def view_all(request):

    """View All view"""

    view_all_list = Advert.objects.all().order_by('date_posted')

    context = {

        "view_all_list": view_all_list

    }

    return render(request, 'view-all.html', context)

my template 


我想获取所有图像的总数,以便我可以在这里使用它


{{items.****}}


慕容森
浏览 158回答 1
1回答

Cats萌萌

要回答您的问题,请添加以下内容作为模型方法:class Advert(models.Model):    ...    @property    def image_count(self):        image_count = 1        if self.image_2:            image_count += 1        if self.image_3:            image_count += 1        if self.image_4:            image_count += 1        if self.image_5:            image_count += 1        return image_count在您的模板中:{{ items.image_count }}但是,这似乎不是一个很好的数据库模式。相反,(对我而言)拥有另一个模型会更有意义,例如class AdvertImage(models.Model):    advert = models.ForeignKey(        Advert,        on_delete=models.CASCADE,        related_name='images',    )    image = models.ImageField()这样您就可以:拥有尽可能多的图像(但仍然强制每个广告的最大值,可能在表单验证或使用表单集)。只需执行类似advert.images.count()获取图像数量或在模板中的操作:{{ advert.images.count }}.减少重复代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python