Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 968
9-bits Avatar asked Nov 03 '11 20:11

9-bits


1 Answers

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.

like image 153
Lycha Avatar answered Sep 22 '22 20:09

Lycha