Django模板遍历具有父ID或PK的项目

时间:2019-01-28 18:58:19

标签: django django-models django-templates django-views

我正在尝试在Django上设置壮观的弹出窗口。 我的目标是在首页概述图库视图中显示一张主图片,单击该主图片将打开一个弹出窗口,其中包含来自同一照片拍摄的相关图像,即具有相同ID或PK的图像。

我尝试应用following approach 但是我只是无法使它正常工作,也许有人可以在这方面帮助我

我的模型。py

class Item(models.Model):
name           = models.CharField(blank=False, max_length=200)    
category       = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
order          = models.IntegerField(blank=True, null=True)
active         = models.BooleanField(blank=True, default=False)
objects        = models.Manager()

class Meta:
    verbose_name_plural = 'items'

def __str__(self):
    return self.name

class ItemImage(models.Model):
image          = ProcessedImageField( 
                                blank=True, 
                                null=True,
                                processors=[ResizeToFit(width=1680, upscale=False)],
                                format='JPEG',
                                options={'quality':90})
order          = models.IntegerField(blank=True, null=True)
main           = models.BooleanField(blank=True, default=False)
cover          = models.BooleanField(blank=True, default=False)
item           = models.ForeignKey(Item, related_name='items', blank=True, null=True, on_delete=models.SET_NULL)
objects        = models.Manager()

class Meta:
    verbose_name_plural = 'item images'

Views.py

def portraits(request):
port = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
portall = ItemImage.objects.filter(item__category__slug='portraits', item__active=True).order_by('item__order')
context = {
    'main_portraits': port,
    'all_portraits': portall
        }
return render(request, 'gallery/portraits.html', context)

和模板:

{% block content %}

<div class="grid">
  {% for pic in main_portraits %}
    <div class="item">
      <div class="item">
          <div class="outer-text">
            <div class="text">
              {{ pic.item.name }}
              <p>Click to view gallery</p>
            </div>
          </div>
          <a><img class="lazy" alt=""
          sizes="(min-width:1400px) 1220px
                (min-width:1000px) 1000px,
                (min-width:500px) 700px,
                (min-width:320px) 420px,
                280px"
          srcset="{{ pic.image_xs.url }} 280w, 
                  {{ pic.image_s.url }} 420w,
                  {{ pic.image_m.url }} 700w,
                  {{ pic.image_l.url }} 1000w,
                  {{ pic.image_xl.url }} 1220w" />
          </a> {{ pic.item.pk }}
      </div>                
      <div class="lazy">
        {% for p in all_portraits %}
          <a href="{{ z.item.pk }}"></a>
        {% endfor %}
      </div>
    </div>
  {% endfor %}
</div>

{% endblock %}

我设置了

z.item.pk 

作为测试,以查看我的任何操作是否导致pk捆绑在一起。例如,第一个for循环返回PK为“ 24”的图片,我需要第二个for-lop仅返回具有相同PK的图像;因此,对于每个图像我认为答案可能与_set.all函数有关,就像上面的相关问题一样,但是我似乎无法使其在我的情况下起作用。感觉就像我在这里缺少什么。

当前输出:

<div class="grid">

    <div class="item">
      <div class="item">
          <div class="outer-text">
            <div class="text">
              Palagā tītā
              <p>Click to view gallery</p>
            </div>
          </div>
          <a><img class="lazy" alt=""
          sizes="(min-width:1400px) 1220px
                (min-width:1000px) 1000px,
                (min-width:500px) 700px,
                (min-width:320px) 420px,
                280px"
          srcset="/media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/958ba5dbee5efe28fd2f5054b8f819e1.jpg 280w, 
                  /media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/02d12ca7f0633fee2fc762cf96f7889e.jpg 420w,
                  /media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/ba5fa6633e92a288e3b2f47a713d64c2.jpg 700w,
                  /media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/fe0d559fef5b02434c43f841005d4961.jpg 1000w,
                  /media/CACHE/images/IMG_8329_3Vi8mYO_GD621ql/96d0e52dff14d1bc4b60bbec674565db.jpg 1220w" />
          </a> 24
      </div>                
      <div class="lazy">

          <a href="24"></a>

          <a href="24"></a>

          <a href="24"></a>

          <a href="26"></a>

          <a href="27"></a>

          <a href="27"></a>

          <a href="30"></a>

          <a href="31"></a>

      </div>
    </div>

2 个答案:

答案 0 :(得分:0)

您可以像这样分解模型,这将使​​查询更加容易。

# models.py
class Item(mdoels.Model):
    name = models.CharField(blank=False, max_length=200)
    category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
    ...
    display_image = models.ProcessedImageField(...)


class ItemImage(models.Model):
    item = models.ForeignKey(Item, related_name='images', blank=True, null=True, on_delete=models.SET_NULL)
    image = models.ProcessedImageField(...)
    ...


#views.py
def portraits(request):
    items = Item.objects.filter(category__slug='portraits', active=True)
    return render(request, 'gallery/portraits.html', context={items: items})

#template
{% for item in items %}

    <h1> {{item.name}} </h1>
    <img src={{item.display_image}} />

    {% for item_image in item.images.all %}
        <img src={{item_image.image}} />
    {% endfor %}

{% endfor %}

答案 1 :(得分:0)

在移交给模板之前,需要预先过滤的查询集,其中包含每个主图像的相关图像。

def portraits(request):
    ports = ItemImage.objects.filter(item__category__slug='portraits', item__active=True, main=True,).order_by('item__order')
    for p in ports:
        # You may not need the item__category__slug filter 
        # if there are only images of the same category 
        # associated with an item.
        # Also, if you want to exclude the main image 
        # from the set of related images, you need to add the filter
        # main=False

        p.related_images = ItemImage.objects.filter(item__category__slug='portraits', item__id=p.item.id)

    context = {
        'main_portraits': ports,
            }
    return render(request, 'gallery/portraits.html', context)

然后,您可以在模板中的main_portraits上循环,并在嵌套循环中获取每个主图像的相关图像:

{% for mainp in main_portraits %}
    {% for im in mainp.related_images %}
         {# do something with the related images #}
    {% endfor %}
{% endfor %}