【问题标题】:Django: Query one to many relationship for existing relationship with certain attributes in the many-modelDjango:在多模型中查询与某些属性的现有关系的一对多关系
【发布时间】:2015-06-24 09:02:38
【问题描述】:

假设我有以下两个模型

Group(Model):
    attribute = CharField()

TranslatedFoo(Model):
    language = ForeignKey(Language)
    country = ForeignKey(Country)
    group = ForeignKey(Group)

现在我想在一个查询中找到所有在其 translatefoo_set 中具有 TranslatedFoo 且 language_code='x' 和 country='y' 在一个查询中的组。是否存在类似:

Group.objects.filter(translatedfoo_set__language__code='x', translatedfoo_set__country__code='y')

我知道这行不通。也许我需要重新考虑我的表格布局

【问题讨论】:

  • 你试过Group.objects.filter(translatedfoo__language_code='x', translatedfoo__country='y')吗? Relevant docs:在页面中搜索“反向”。
  • 是的,这确实有效。谢谢!

标签: python django django-queryset one-to-many


【解决方案1】:

正确的查询不包括_set部分:

Group.objects.filter(translatedfoo__language_code='x', translatedfoo__country='y')

this doc page 上搜索“reverse”以了解更多详情。

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 2018-05-21
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多