Reputation: 12433
I am using Django3
and model
I want to get the data of Distance
from one city to another city.
But in the database, only the distance A to B is stored ( because distance of B to C is the same)
So, what I want to is fetch the correct row, regardless the order of cities.
I can do this with use these two sentences and error check each.
Distance.objects.get(key_first=firstcity, key_second=secondcity)
Distance.objects.get(key_second=secondcity, key_second=firstcity)
However it looks a bit awkward and it requres two times DB fetch, Is there any smarter way like this below??
Distance.objects.get((key_first=firstcity, key_second=secondcity) | (key_second=secondcity, key_second=firstcity))
Upvotes: 0
Views: 59
Reputation: 2088
You almost hit it with the second example:
from django.db.models import Q
Distance.objects.filter(Q(key_first=firstcity, key_second=secondcity) | Q(key_second=secondcity, key_second=firstcity)).first()
Upvotes: 1