Django how to include all columns from one table, but a only subset of columns in a different table, using tbl.only?

213 views Asked by At

I want to join a child table to the parent table, and return all columns from the child table (child.*), but only specific columns from a parent table (parent.foo, parent.bar), using only but not defer.

Is there any syntax to issue a SQL similar to the following:

select child.*, 
    parent.foo, parent.bar
from child join parent on child.parent_id = parent.id

I do not want to use defer, because the parent table has even more columns than the child table.

I currently have to spell out every column that I want using only:

Child.objects.select_related('parent').only(
    'id', 'name', 'creation_date', 
    'parent__foo', 'parent__bar'
).all()

But I would like to include all the columns from Child.

1

There are 1 answers

0
brwa ata On

You can do this

Child.object.select_related('parent').only(*[f.get_attname() for f in Child._meta.fields], 'parent__foo', 'parent__bar').all()