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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With