1👍
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-model -
Substitute the default
User
model with a model of your own: https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#substituting-a-custom-user-model -
Use "reverse" relationship queries: https://docs.djangoproject.com/en/4.1/topics/db/queries/#lookups-that-span-relationships
I hope this solves your problem.