Reputation: 1270
I am Building a BlogApp and I am stuck on a Problem.
What i am trying to do
I am trying to access all the data of only one Model instance
in Function Based View
.
In Brief
I am trying to show all the posts liked by a all the users
in a particular page.
What have i tried
1). post = Paintings.objects.filter(likes=pk)
This didn't work because it only show the logged in user's posts. AND i want to get all the posts that are liked.
2). post = Paintings.objects.all()
This also didn't work for me.
models.py
class Post(models.Model):
post_owner = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name='post_like', blank=True)
views.py
def featured_paintings(request,pk):
post = Post.objects.filter(likes=pk)
context = {'post':post}
return render(request, 'mains/featured_posts.html', context)
I don't know what to do.
Any help would be appreciated.
Thank You in Advance
Upvotes: 0
Views: 690
Reputation: 21807
Try excluding Posts that match likes=None
this will give you all instances who have atleast one like:
post = Post.objects.exclude(likes=None)
Upvotes: 1
Reputation: 32244
You can use the isnull
lookup to filter a relationship having at least one related object
Post.objects.filter(likes__isnull=False)
Upvotes: 1