Django queryset select all from multiple tables

I want to select all columns from multiple table join using django queryset corresponding to following sql

select user.*, address.*, contact.* from user left join address on user.id = address.userid left join contact on user.id = contact.userid

I have following python
User.objects.values() to get all user data.
User.objects.values(first_name, last_name, contacts__number, addresses__zip) to get specific columns

But I dont know how to get all columns from all 3 tables something like

User.objects.values(*, contacts__*, addressess__*)

If you have defined the ForeignKey relationships on the User class, you can use:

users = User.objects.select_related("Address", "Contact").all()

Then you can access the related object on the User object as as attribute:

for user in users:
    print(user.address)
    print(user.contact)

Actually, the select_related() hint is not necessary and you can access the related record as an attribute in any case, it just prevents a separate database query for every access.

If you are using the User model in the Django auth app, you can go either of these routes to achieve your goal:

I hope this solves your problem.

Back to Top