Anoop K George
Anoop K George

Reputation: 1755

Django, check if an object present in query set using exists() method

I have a below model,

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    head = models.CharField(max_length=255)
    authors = models.ManyToManyField(Author)

I have created an object in Entry model, when I try to check if there is any objects in Entry model it shows error as attached image

enter image description here

Upvotes: 0

Views: 1896

Answers (2)

ktowen
ktowen

Reputation: 336

If you need the object you can do:

entry = Entry.objects.filter(pk=1).first()
if entry:
    # …
else:
    # …

The .first() method returns None if the queryset is empty.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

It is Entry.objects.filter(pk=1).exists(), since .get() is not a QuerySet, but an Entry object in this case. So you check with:

if Entry.objects.filter(pk=1).exists():
    # …
else:
    # …

Here however, it is probably simpler to work with a try-except clause, and thus work in an EAFP style [wiki]:

try:
    entry = Entry.objects.get(pk=1)
    print('k')
except Entry.DoesNotExists:
    print('false')

Upvotes: 3

Related Questions