matching query does not exist Error in Django

后端 未结 6 597
情歌与酒
情歌与酒 2020-11-29 20:35

I have implemented a password recovery functionality in django. With my method, the new password will be sent to the email id entered. It works fine when given the correct e

6条回答
  •  暖寄归人
    2020-11-29 20:42

    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.

提交回复
热议问题