class Nutrient(models.Model):
tagname = models.CharField(max_length=10)
class FoodNutrientAmount(models.Model):
nutrient = models.ForeignKey(Nutrient)
food = models.ForeignKey(Food)
amount = models.FloatField()
class Food(models.Model):
nutrients = models.ManyToManyField(
Nutrient,
through=FoodNutrientAmount,
)
tagname=FOL
したがって、リスト内包表記を使用して、栄養素の量で注文された食品を取得できます。
ordered_fnas = FoodNutrientAmount.objects.filter(
nutrient__tagname="FOL"
).order_by('-amount')
ordered_foods_by_most_fol = [fna.food for fna in ordered_fnas]
すべてをメモリに入れずに、クエリセットのような反復可能なものを取得できますか?
たぶん、またはを使用して別のアプローチがありますFood.objects.annotate
かextra
?現時点では、それを行うための優れた方法を考えることはできません。
私はvalues_listに近づくことができます。しかし、必要なオブジェクトのクエリセットではなく、pkの順序付きリストを取得しFood
ます。
FoodNutrientAmount.objects.filter(
nutrient__tagname='FOL'
).order_by('-amount').values_list('food', flat=True)