【问题标题】:join 2 tables that have no foreign key to eact other连接两个没有外键的表
【发布时间】:2021-03-08 04:51:26
【问题描述】:
class A(Base):
    number = models.IntegerField(default=None)
    ...

class B(Base):
    head_number = models.IntegerField(default=None)
    ...

有 2 个模型彼此没有关系,如何在 django orm 中使用注释在下面编写查询?

Select * from A
inner join B on A.number = B.head_number

我曾尝试使用extra(),它可以工作,但我想使用annotate()。 它不能改变任何模型。 有什么办法吗?

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    您可以使用in 字段查找进行过滤。

    A.objects.filter(number__in=B.objects.values_list('head_number', flat=True))
    

    此查询集 B.objects.values_list(..) 将被评估为子选择语句(where 子句中的子查询)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多