简体   繁体   English

如何在 django 视图中访问外部表字段

[英]how to access foreign table field in django view

I have two models, the plans model & plans features ( foreign relation with plans table), given below:我有两个模型,计划 model 和计划特征(与计划表的关系),如下所示: 模型.py

Following is the view which returns an object of features for each plan:以下是为每个计划返回 object 功能的视图: 视图.py

Now I want to access, the "price" field of the plans table (model).现在我想访问计划表(模型)的“价格”字段。 How this is possible?这怎么可能? my Django template is the following which doesn't work:我的 Django 模板如下不起作用: 模板代码

I belive there is solution to this, I would love hear from you.我相信有解决方案,我很想听听你的意见。 thank you谢谢你

First of all, when you use filter returns a queryset, not a single object so you can not direct access the foreign key with dot首先,当你使用过滤器返回一个查询集,而不是一个单一的 object 所以你不能用直接访问外键

Solution:解决方案:

  1. Use .get()使用.get()
  2. Use .filter().first()使用.filter().first()

You can choose from above two.您可以从以上两个中进行选择。

Assuming you have unique entries for basic, standard and professional packages假设您有基本、标准和专业套餐的唯一条目

plans_features.objects.get(plan__title="BASIC")
plans_features.objects.get(plan__title="STANDARD")
plans_features.objects.get(plan__title="PROFESSIONAL")
<ul class="deal-item">
{% basic.plan.price %}
</ul>
<ul class="deal-item">
{% standard.plan.price %}
</ul>
<ul class="deal-item">
{% professiona.plan.price %}
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM