Reputation: 63
I would like to get a user queryset who commented in certain post. Assume that there is a post(id=3), and there 8 people commented on it. I want to notify something to 8 people, so I want to get 8 people's queryset(user objects). How can I do it?
I have model User, Post, and Comment.
For example,
User.objects.get(comment__Post.objects.filter(id='3'))
like this way. (of course, the upper doesn't work)
Help me!
User model is Django User model.
class Post(models.Model):
post_id = models.CharField('username', max_length=150)
...
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
com_id = models.CharField('username', max_length=150)
....
Upvotes: 0
Views: 1261
Reputation: 1099
Ideally your models should look like the following
class Post(models.Model):
posted_by = models.ForeignKey(User, on_delete=models.CASCADE)
...
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.CharField(max_length=100)
commented_by = models.ForeignKey(User, on_delete=models.CASCADE)
And your requirement can be achieved through the following query
post = Post.objects.get(id=3)
user_ids = list(Comment.objects.filter(post=post).values_list('user__id', flat=True))
This will return the list of user ids
If you need queryset,
users = User.objects.filter(id__in=user_ids)
Upvotes: 1
Reputation: 345
In my opinion you should add a OneToOneField
to the model Comment
and to the model Post
that relate to the User
model like this:
from django.conf import settings
...
class Post(models.Model):
...
user = models.OneToOneField(settings.User, related_name="posts")
...
class Comment(models.Model):
...
user = models.OneToOneField(settings.User, related_name"comments")
post = models.ForeignKey(Post, related_name="post_comments")
...
The for your queryset you will be able to do:
User.objects.get(posts__id=3)
for comments in Comment.objects.get(post_comments__id=3):
comments.user # this are the user that commented on a certain post.
Upvotes: 1