Reputation: 45
I'm having problems trying to use the queryset filter with my models. It is a control for posts in groups.
This is my code:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
I'm trying to get all posts from a group with the title "title":
queryset_list = Control.objects.filter(group__control="title")
My models might nit be right, I'm new to this. Any help?
Upvotes: 2
Views: 10449
Reputation: 2454
First, you should add a ManyToManyField
on Group
(docs):
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
posts = models.ManyToManyField('Post', through='Control')
The other two models remain the same, but now you can easily grab posts for a Group:
posts = Group.objects.get(title='some title').posts.all()
Upvotes: 1
Reputation:
Maybe it typo error?
queryset_list = Control.objects.filter(group__title="title")
# ^^^^^^
posts_title = queryset_list.values('post__title')
Upvotes: 3