[Answer]-Django ORM: Filter with OR not returning object

1👍

using .get() is problematic. It will return an object if using a QuerySet with only one object, but if there’s more it will throw a MultipleObjectsReturned error and if the QuerySet is empty it will throw a DoesNotExist Error.

So the problem is very probably a QuerySet that does not apply to the specific condition you require. The solution? Return a default value.

Finally, you can use [0] instead of limiting to one object and then fetching it, and also, as @pythonishvili mentioned, you could pre-filter on the incentive. summing it all up, it should look like so (I split the query across multiple lines for better readability):

qs = Recipient.objects.filter(incentive__id__exact=incentive_id) #common filter
qs = qs.filter(models.Q(mobil‌​e=mobile, email=email) | 
               models.Q(friends_mobile=mobile, friends_email=email))
qs = qs.order_by('-date_created')
return qs[0] if qs else None #or any other default you'd like to use
👤yuvi

Leave a comment