Lars
Lars

Reputation: 1270

How to get only one instance of a model in views

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)

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

Answers (2)

Abdul Aziz Barkat
Abdul Aziz Barkat

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

Iain Shelvington
Iain Shelvington

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

Related Questions