Is there a way to search a Django queryset by id or a combination of fields without making additional calls to the database.
Would something like this be a single db query?
qs = Employee.objects.filter(restaurant='McDonalds')
emp1 = qs.filter(id=1)
emp2 = qs.filter(id=2)
emp3 = qs.filter(id=3)
Or is the only way to do something like this to map ids to the model instances beforehand?
qs = Employee.objects.filter(restaurant='McDonalds')
emp_map = {instance.id: instance for instance in qs}
emp1 = emp_map.get(1)
emp2 = emp_map.get(2)
emp3 = emp_map.get(3)
You can query the three elements in one query:
# filter on the primary key as well ↓
qs = Employee.objects.filter(restaurant='McDonalds', pk__in=[1, 2, 3])
data = {employee.pk: employee for employee in qs}
emp1 = data.get(1)
emp2 = data.get(2)
emp3 = data.get(3)
The advantage of using pk__in=[1, 2, 3]
is that you limit the number of records the database retrieves to at most the three we are interested in. This will reduce the work the database has to do, as well as the bandwidth from the database to the Django/Python layer.