models.py:Django的prefetch_related與過濾
class Ingredient(models.Model):
_est_param = None
param = models.ManyToManyField(Establishment, blank=True, null=True, related_name='+', through='IngredientParam')
def est_param(self, establishment):
if not self._est_param:
self._est_param, created = self.ingredientparam_set\
.get_or_create(establishment=establishment)
return self._est_param
class IngredientParam(models.Model):
#ingredient params
active = models.BooleanField(default=False)
ingredient = models.ForeignKey(Ingredient)
establishment = models.ForeignKey(Establishment)
我需要parametrs獲取所有成分爲Establishment
。首先我獲取Ingredients.objects.all()
並使用所有參數,如Ingredients.objects.all()[0].est_param(establishment).active
。我如何使用django 1.4 prefetch_related來減少sql查詢?可能是我可以使用其他方式來存儲個人Establishment
屬性Ingredient
?
可能的重複[Filter on prefetch \ _related in Django](http://stackoverflow.com/questions/10915319/filter-on-prefetch-related-in-django) – akaihola