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:
Attach a model as the profile to DJango
User
model: https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#extending-the-existing-user-modelSubstitute the default
User
model with a model of your own: https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#substituting-a-custom-user-modelUse "reverse" relationship queries: https://docs.djangoproject.com/en/4.1/topics/db/queries/#lookups-that-span-relationships
I hope this solves your problem.