简体   繁体   中英

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: 模型.py

Following is the view which returns an object of features for each plan: 视图.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: 模板代码

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

Solution:

  1. Use .get()
  2. Use .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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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