【问题标题】:Django ORM querysetDjango ORM 查询集
【发布时间】:2021-07-25 08:38:05
【问题描述】:

我正在学习 Django ORM 以及如何进行查询,假设我有两个模型

class Company(models.Model):
    structure = IntegerField()

class Customer(models.Model):
    created_at = DateTimeField(default=now)
    company = ForeignKey(Company)
    friend = BooleanField()
  • 我正在编写一个函数,它可以获取最近创建的客户为 friend=True 的所有公司。
def get_companies_with_recent_friend():
  """"
    Returns
    -------
    `list(Company, ...)`
    """
    raise NotImplementedError

【问题讨论】:

    标签: python-3.x django django-models django-queryset


    【解决方案1】:

    您可以使用子查询来确定这一点,因此:

    from django.db.models import OuterRef, Subquery
    
    Company.objects.annotate(
        last_is_friend=SubQuery(
            Customer.objects.filter(
                company=OuterRef('pk')
            ).order_by('-created_at').values('friend')[:1]
        )
    ).filter(last_is_friend=True)

    因此,子查询将生成与Company 链接的Customers 的有序集合,我们为这些客户中的第一个Customer 选择friend 值。这就是注解的作用。

    最后我们过滤掉没有friend作为最后一个CustomerCompanys。

    【讨论】:

    • 如果我这样做会发生什么Company.objects.filter(customer__friend=True).order_by('-customer__created_at')?
    • @daneilJames:您只需获得至少一个Customer是朋友的所有Companys。 Company 将在 QuerySet 中重复的次数与相关的 Customers 是朋友的次数一样多,Companys 将按这些 Customers 中的 created_at 排序。跨度>
    猜你喜欢
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2020-12-03
    • 2023-03-03
    • 2022-01-18
    • 2023-03-10
    • 2015-06-25
    相关资源
    最近更新 更多