Reputation: 1620
In Django, MySQL setup the following query
data = Recording.objects.get(Q(name='xyz') | Q(name="default"))
This throw MultipleObjectsReturned
as both xyz
and default
records are present in the DB and MySQL returns both object on OR operation
queries. (That's correct MySQL behavior)
Is there a way in Django/MySQL where the above query would return only one object even when both the records are present in DB?
Note: Constrain is only 1 query should be used to fetch the data and the query should return specific object (i.e xyz) first.only if it is not present shall the default
object be returned
Upvotes: 0
Views: 223
Reputation: 19922
.get
should be used to retrieve a single record, as you noticed. Use filter
otherwise:
data = Recording.objects.filter(Q(name='xyz') | Q(name="default")).first()
If which one matters, use order_by
to arrange the order.
You could also use:
data = Recording.objects.filter(Q(name='xyz') | Q(name="default"))[0]
Which is practically the same. For more information see Django docs.
Upvotes: 1