Reputation: 1755
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
Upvotes: 0
Views: 1896
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
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