亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法從模型中獲取并顯示用戶發布的每個廣告的圖像數量

有沒有辦法從模型中獲取并顯示用戶發布的每個廣告的圖像數量

慕容森 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 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號