Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and reverse relations from foreign keys

suppose the following simple models:

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    author = models.ForeignKey(User, related_name='author_set')

How can I get all the authors that participated in a particular blog (i.e. pk=1)? I tried something like this, but it didn't work.

User.objects.author_set.filter(blog=Blog.objects.get(pk=1))

Many thanks in advance!

like image 385
Clash Avatar asked Apr 11 '12 18:04

Clash


1 Answers

User.objects.filter(author_set__blog__pk=1)

I wasn't paying attention to your related name, so the code above (revised) now uses the proper related name. However, this is a really bad related name. The related name should describe what's on the opposite side, i.e. Entry. So really it should be related_name='entry_set'. However, that's the default anyways, so you can remove related_name if you just want that. I would typically use a simple pluralized version of the related class, which would be in this case related_name='entries'. Or, you might want to use something like "blog_entries" to be more specific.

like image 158
Chris Pratt Avatar answered Oct 02 '22 20:10

Chris Pratt