9

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?

9-bits
  • 10,395
  • 21
  • 61
  • 83

1 Answers1

18

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.

Lycha
  • 9,937
  • 3
  • 38
  • 43
  • Since they want every `Video` owned by `u`, I'd argue they should be going through `Video.objects.filter(user__pk=u.pk)` instead. – desfido Nov 03 '11 at 20:34
  • 1
    @desfido My way should return set of all videos that have the user (u) as "user". The original "owner" label is misleading in that way. Your way works too, it's just bit more work. – Lycha Nov 03 '11 at 20:41
  • Fair enough. Upon reflection, I agree the `u.video_set.all()` is probably easier to come back to & interpret intent for. – desfido Nov 03 '11 at 20:46