[Django]-Matching query does not exist Error in Django

184๐Ÿ‘

โœ…

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None

I also see youโ€™re storing your passwords in plaintext (a big security no-no!). Consider using the built-in auth system instead.

๐Ÿ‘คSam Dolan

15๐Ÿ‘

As mentioned in Django docs, when get method finds no entry or finds multiple entries, it raises an exception, this is the expected behavior:

get() raises MultipleObjectsReturned if more than one object was
found. The MultipleObjectsReturned exception is an attribute of the
model class.

get() raises a DoesNotExist exception if an object wasnโ€™t found for
the given parameters. This exception is an attribute of the model
class.

Using exceptions is a way to handle this problem, but I actually donโ€™t like the ugly try-except block. An alternative solution, and cleaner to me, is to use the combination of filter + first.

user = UniversityDetails.objects.filter(email=email).first()

When you do .first() to an empty queryset it returns None. This way you can have the same effect in a single line.

The only difference between catching the exception and using this method occurs when you have multiple entries, the former will raise an exception while the latter will set the first element, but as you are using get I may assume we wonโ€™t fall on this situation.

Note that first method was added on Django 1.6.

8๐Ÿ‘

I also had this problem.
It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion.
(Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()
๐Ÿ‘คRobse

4๐Ÿ‘

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()
๐Ÿ‘คvikasvmads

2๐Ÿ‘

In case anybody is here and the other two solutions do not make the trick, check that what you are using to filter is what you expect:

user = UniversityDetails.objects.get(email=email)

is email a str, or a None? or an int?

2๐Ÿ‘

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False
๐Ÿ‘คMd Mehedi Hasan

-1๐Ÿ‘

The problem is occurred when you try to match the email while the database is empty. So, if you want to solve this type of error try to put it into try except block. The example is โ€“

try:
    user = UniversityDetails.objects.get(email=email)
except UniversityDetails.DoesNotExist:
    user = None
๐Ÿ‘คMehedi Abdullah

Leave a comment