【问题标题】:Is it possible to filter models in django templates?是否可以在 django 模板中过滤模型?
【发布时间】:2017-12-30 11:39:48
【问题描述】:

我在下面添加了我的视图和模板代码。我的问题,我怎样才能得到鸟(模型 1)和相应鸟的详细信息(模型 2) --------查看--------

all_birds = Bird.objects.all()
detail = Detail.objects.all()
template = loader.get_template('bird/bird.html')
contex = {
    'all_birds': all_birds,
    'details': detail,
}
return HttpResponse(template.render(contex, request))

--------模板----------

{% for birds in all_birds %}
        <div class="container">
            <div class="row">
                  <div id="board" data-columns>
                    <div class="item">
                        <div class="ani-box">
                            <a href="{% static 'bird/images/img_10.jpg'%}" class="image-popup fh5co-board-img">
                                 <img src="{% static 'bird/images/img_10.jpg'%}" alt="No Image available"></a>
                        </div>
                    </div>
                  </div>
             </div>
        </div>
    {% endfor %}

【问题讨论】:

标签: python django django-models django-templates


【解决方案1】:

假设它们通过外键关联,您将需要获取每只鸟各自的详细信息。

如果您有“Widget”和“Specs”的模型,例如:

class Widget(models.Model):
    name = models.CharField(max_length=255)
    specs = models.ForeignKey('Specs')

class Specs(models.Model):
    foo = models.IntegerField()
    bar = models.UrlField()

如果有所有小部件的上下文,即{'widgets': Widget.objects.all()},当您迭代它们时,您可以访问它们的Specs 对象。

{% for widget in widget %}
   <ul>
   <li>{{ widget.name }}</li>
   <li>{{ widget.specs.foo }}</li>
   <li>{{ widget.specs.bar }}<li>
   </ul>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2012-07-28
    • 2011-10-08
    • 2011-09-12
    • 1970-01-01
    • 2011-07-10
    • 2018-05-07
    • 2022-10-25
    相关资源
    最近更新 更多