In Django, how can you get all related objects with a particular User foreign Key

9-bits picture 9-bits · Nov 3, 2011 · Viewed 20.2k times · Source

I have something like this:

class Video(models.Model):
    user = models.ForeignKey(User, related_name='owner')
    ...

and I'm trying to access all the videos a particular user has by doing something like:

u = User.objects.get(pk=1)
u.video_set.all()

and I get the error 'User object has no attribute video_set'

Am I doing something wrong?

Answer

Lycha picture Lycha · Nov 3, 2011

related_name is the name for referring to it from the target-model (User in this case). The way you have set it you should be calling:

u = User.objects.get(pk=1)
u.owner.all()

However for clarity you probably should set the related name to something like related_name='video_set' (which is default name for it btw). Then you could call u.video_set.all() which looks more logical.