'object has no attribute 'exists'

I am using Django 1.3 and trying to use .exists() on a model entry but get the error listed below. Exists() was included in Django 1.2 so I should have access to it. I verified my version using django.get_version and it was okay. Querying MyModel based on pk only returns an entry but querying with .exists() throws an error. Do I need to imports something?

>>> m = MyModel.objects.get(pk=1)
>>> m
<MyModel: Model field entry 1>
>>> m = MyModel.objects.get(pk=1).exists()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'MyModel' object has no attribute 'exists'


Solution 1:[1]

I'm using Django 1.7 on my project and my codes like :

try:
    temp_query_set = YourModelName.functionName()
except ObjectDoesNotExists:
    <do something> 

note that, my code (at first) using if query_set.exists() it works fine when there is no query set returned, but raise error object does not have attribute 'exists' when there is something returned. so pls try avoid using if <something>.exists() CMIIW

Solution 2:[2]

try use .filter() instead .get(), like this:

m = MyModel.objects.filter(pk=1).exists()
y = MyModel.objects.filter(pk=2).exists()
print(m)
print(y)

output must to be a bool, exemple:

False
True

suposing that m does not exist and y exists

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guhkun13
Solution 2 Nicholas Barros