[Django]-Minimizing DB hits in Django: .values_list() dependent on previous .filter() clause

2👍

I think your best bet is the use of the Q object, something like

qs = Combination.objects.filter(Q(food1=food_id)|Q(food2=food_id).values_list('food1', 'food2')
combinations = set()
for row in qs:
   if row[0] == food_id:
       combinations.append(row[1])
   else:
       combinations.append(row[0])
👤dvd

2👍

Isn’t

itertools.chain(Food(id=food_id).food1.all(), Food(id=food_id).food2.all())

what you’re after?

And if order of Foods in combinations is irrelevant, why not use a ManyToManyField(Food) on Combination?
Then Food(id=food_id).combination_set.all() will be all combinations that have that particular food in them.

Leave a comment