2015-08-27 138 views
1

的多個字段我有三個型號:Django的過濾器通過相關模型

class Product(models.Model): 
    name = models.CharField(verbose_name='Name', max_length=100, unique=True, db_index=True) 

class Recipe(models.Model): 
    pass 

class Ingredient(models.Model): 
    recipe = models.ForeignKey(Recipe, verbose_name='Recipe', db_index=True) 
    product = models.ForeignKey(Product, verbose_name='Product') 
    amount = models.DecimalField(verbose_name='Amount', max_digits=8, decimal_places=2) 

如何過濾僅具有給定數量的給定成分配方對象? 。

對於離,我需要僅具有以下inredients食譜:

  • ID = 1和量< = 10,和
  • ID = 2和量< = 15

如果有其他成分,這些配方不應該通過查詢返回。

回答

1

您可以使用q object進行查詢span through relationship並進行復雜查詢。例如,在你的情況。

Recipe.objects.filter(Q(Q(ingredient_set__id=1, ingredient_set__amount__lte=10) | Q(ingredient_set__id=2, ingredient_set__amount__lte=15))) 
+0

謝謝! Q對象似乎解決了我的問題。 – audciz

+0

如何排除含有其他成分的物品? – audciz

+0

audciz,[請參閱Q的文檔](https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects)您可以使用'〜'來否定'Q'對象,你可以用''''按''''把它們和其他'Q'對象結合起來。 –