首页 > 解决方案 > 有没有办法从模型中获取并显示用户发布的每个广告的图像数量

问题描述

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

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 

{% for items in view_all_list %}
    <a href="" class="col card-sm">
      <div class=" row">
        <span class="numbertext"><i style="margin-right: 4px;" class="fas fa-camera"></i>{{items.****}}</span>
        <img src="{{items.image_primary.url}}" alt="">
      </div>
      <div class="row" title="{{items.title}} | {{items.price}}">
        <h5>{{items.title}}</h5>
        <h4>{{items.price}}</h4>
      </div>
    </a>
    {% endfor %}

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

{{items.****}}

标签: pythondjango

解决方案


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

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. 减少重复代码。

推荐阅读