I have created a model which has foreign key to the django.contrib.auth.models User model. I need to retrieve the value the foreign key is referring to. But how to do that?
E.g. my model is
from django.contrib.auth.models import User
def FooModel(models.Model):
user = models.ForeignKey(User)
then I know I can either use:
FooModel.objects.get() or FooModel.objects.filter() but as far as I know they will only return entries from the FooModel only. So how do I retrieve from the User model?
You can use
..That wxample will return you the username of the related user. Also you can createjoinsusing__on the query filtering. Like:But, since you are building your query on
FooModel, you will always getFooModelresults. So you have you use.to use foreignkey relations to get to the requiredUserfield.EDIT:
Django also allows you to use
reverse relationson querysets, so even thoughUsermodel do not have a foreignkey toFooModelon its model structure, you can use reverse relation ofFoomodel.userforeignkey like:will return you the user which have
FooModelrecord with a foreign key to hisUserrecord and foofield value of Beatles