简体   繁体   中英

How can I access ALL model attributes from two tables joined together using django ORM

I want to access all values from two related tables that I joined together based on one of the tables attributes:

obj = A.objects.filter(B__sample='sample_name').select_related()

but when i do:

{% for o in obj %}

    {{o.sample}}
    {{o.results}}
    {{o.qc}}

{% endfor %}

only o.results and o.qc (from table A) are returned, o.sample is not returned (from table B)

how do i access all of the values from table A and B from my queryset object?

obj = A.objects.filter(B__sample='sample_name').select_related('b')

试试这个,用小外国模特的名字

You've misunderstood how models work in Django.

sample is an attribute from model B, and will always be that. Django won't ever add it as a direct attribute to model A; that would be confusing.

You still access it via an instance of model B; the magic that Django gives you is that oB (or whatever your ForeignKey is called) will access that model B instance, so you can do oBsample . Since you've used select_related , that won't incur another database hit.

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