Django模板中的外键关系 [英] Foreign key relation in Django template

查看:52
本文介绍了Django模板中的外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经问过很多遍了,但是我仍然无法解决.

I know this question is asked before many times but I still can't solve it.

model.py

class Awb (models.Model):
    awb_id = models.CharField(primary_key=True, max_length=50)
    awb_shipment_date = models.DateTimeField()
    awb_shipper = models.CharField(max_length=250)
    awb_sender_contact = models.CharField(max_length= 50)

class History (models.Model):
    history_id = models.AutoField(primary_key=True)
    awb = models.ForeignKey(Awb)
    history_city_hub = models.CharField(max_length=250)
    history_name_receiver = models.CharField(max_length=250)

view.py

def awb_list_view(request):
    data = {}
    data['awb'] = Awb.objects.all()
    data['history'] = History.objects.all()
    return render(request, 'portal/awb-list.html', data)

模板

{% for s in awb.history_set.all %}
    {{ s.awb_id }}
    {{ s.history_id }}
{% endfor %}

当我使用此代码尝试时,模板中没有结果.我想在模板中显示awb_id和history_id.你能帮我吗?

When I tried it with this code, there is no results in templates. I want to show awb_id and history_id in templates. Could you help me?

推荐答案

首先让我们看一下查看代码...

First let's take a look at the view code...

def awb_list_view(request):
    data = {}
    data['awb'] = Awb.objects.all()
    data['history'] = History.objects.all()
    return render(request, 'portal/awb-list.html', data)

传递给模板的上下文词典包含一个带有键"awb"的项以及相应的QuerySet Awb.objects.all().

The context dictionary being passed to the template contains an item with key 'awb' and respective QuerySet Awb.objects.all().

现在让我们看一下循环模板...

Now let's take a look at the template for loop...

{% for s in awb.history_set.all %}

此循环模板标签的开头正尝试产生一组反向的History对象.为了实现这一点,我们将需要一个AWB对象实例.取而代之的是,"awb"变量是一个QuerySet,它已作为上下文传递给模板.

This opening for loop template tag is trying to produce a reverse set of History objects. In order to achieve this, we would need a single AWB object instance. Instead, the 'awb' variable is a QuerySet which was passed as context to the template.

如果此代码的目的是显示所有AWB对象及其相关的History对象,则以下模板代码应有效.

If the goal of this code is to show all AWB objects with their related History objects, the following template code should be valid.

{% for awb_obj in awb %}
    {% for history_obj in awb_obj.history_set.all %}
        {{ awb_obj.id }}
        {{ history_obj.id }}
    {% endfor %}
{% endfor %}

这篇关于Django模板中的外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆