为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容森 2022-06-07 19:55:28
我正在尝试获取用户发布的每个广告的图像总数。我想在我的模板上显示这个计数。我在网上尝试了几种解决方案,看看我是否可以让它工作,但我有点碰壁了。这是我在电子商务网站上看到的;所以我知道这是可能的。请帮忙...My Modelclass 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.titlemy Viewdef 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.****}}
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

要回答您的问题,请添加以下内容作为模型方法:


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

这样您就可以:

  1. 拥有尽可能多的图像(但仍然强制每个广告的最大值,可能在表单验证或使用表单集)。

  2. 只需执行类似advert.images.count()获取图像数量或在模板中的操作:{{ advert.images.count }}.

  3. 减少重复代码。


查看完整回答
反对 回复 2022-06-07
  • 1 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号