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

29.3k views Asked by At

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?

1

There are 1 answers

3
Lycha On BEST ANSWER

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.