【问题标题】:how to construct this Django ORM queryset query?如何构造这个 Django ORM 查询集查询?
【发布时间】:2023-03-03 10:00:01
【问题描述】:

我正在尝试确定如何构建查询。我有两个来自外部数据库的模型,我试图将它们导入到不同的架构中。源数据有三个模型:

class Group(model):
    ...
    name = models.CharField()

class Person(model):
    ...
    name = models.CharField()

class Membership(model):
    ...
    status = models.CharField()
    created_date = models.DateTimeField()
    modified_date = models.DateTimeField()
    person = models.ForeignKey(
        'Person',
        related_name='memberships',
    )
    group = models.ForeignKey(
        'Group',
        related_name='memberships',
    )

在会员资格中,我有代表人和乐队的字段,包括创建日期和更新日期,以及其他相关数据。

问题出在:Membership 行没有任何表示规范记录的字段,它们混合并匹配人员、日期和其他数据。

我目前正在做的是获取给定乐队的所有会员资格,对他们进行不同的乐队和个人组合,并使用这些结果再次查询会员资格以获取每个特定组合的最新实例。虽然这行得通,但正如您可能想象的那样,它的速度慢得无法形容,我知道一定有更好的方法。

所以我正在寻找如何使用一些高级 django 查询表达式(Window?Over,F-expressions?)在数据库上尽可能多地完成这项工作。

这是获取我想要的记录的代码:

groups = (the groups I want)
for group in groups:
    unique_members = group.members.values(
        'person',
        'group',
    ).distinct()
    for member in members:
        current_member = group.members.filter(
            person__id=member['person'],
            group__id=member['structure'],
        ).lastest('created_date', 'modified_date')

current_member 是该独特个人/组组合的最新成员资格条目。

所以对于这样的成员列表:

Person           Group        Created     Status
John Lennon      Beatles      1960-01-01  Current
Paul McCartney   Beatles      1960-01-01  Current
Pete Best        Beatles      1960-01-01  Expired
George Harrison  Beatles      1960-01-01  Current
Ringo Starr      Beatles      1962-01-01  Expired
Pete Best        Beatles      1964-01-01  Expired
Ringo Starr      Beatles      1966-01-01  Current

我想要以下列表:

John Lennon      Beatles      1960-01-01  Current
Paul McCartney   Beatles      1960-01-01  Current
Pete Best        Beatles      1964-01-01  Expired
George Harrison  Beatles      1960-01-01  Current
Ringo Starr      Beatles      1966-01-01  Current

从单个查询生成。

谢谢!

【问题讨论】:

  • 你能分享一下组和会员模型类吗?
  • 当然(已编辑),但它们并没有什么特别之处。
  • 看圣地亚哥的回答,我觉得还可以
  • 它确实回答了这个问题,所以我会接受它。但更长的答案是“取决于数据库后端”。例如,可能在 PostgreSQL 上,而不是在 MySQL 中(至少不能通过 ORM。)

标签: python django django-models django-queryset django-orm


【解决方案1】:

您可以首先按所需条目对您的成员查询进行排序,然后获取 distict 值。这个问题可能会对您有所帮助:

Django query: get the last entries of all distinct values by list

【讨论】:

  • 这确实回答了这个问题,所以我会接受它。但更长的答案是“取决于数据库后端”。例如,可能在 PostgreSQL 上,而不是在 MySQL 中(至少不能通过 ORM。)
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 2012-03-28
  • 2014-10-09
相关资源
最近更新 更多