自己加入django ORM [英] Self join with django ORM

查看:115
本文介绍了自己加入django ORM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

class Trades(models.Model):  
    userid     = models.PositiveIntegerField(null=True, db_index=True)
    positionid = models.PositiveIntegerField(db_index=True)
    tradeid    = models.PositiveIntegerField(db_index=True)
    orderid    = models.PositiveIntegerField(db_index=True)  
    ...

我想执行下一个查询:

select *
from trades t1
inner join trades t2
ON t2.tradeid = t1.positionid and t1.tradeid = t2.positionid

可以用没有使用Django ORM的黑客来完成吗?
Thx!

can it be done without hacks using Django ORM? Thx!

推荐答案

选择* ...
将需要更多的工作。如果您可以从右侧缩小所需的列

select * ... will take more work. If you can trim back the columns you want from the right hand side

table=SomeModel._meta.db_table
join_column_1=SomeModel._meta.get_field('field1').column
join_column_2=SomeModel._meta.get_field('field2').column
join_queryset=SomeModel.objects.filter()
# Force evaluation of query
querystr=join_queryset.query.__str__()
# Add promote=True and nullable=True for left outer join
rh_alias=join_queryset.query.join((table,table,join_column_1,join_column_2))
# Add the second conditional and columns
join_queryset=join_queryset.extra(select=dict(rhs_col1='%s.%s' % (rhs,join_column_2)),
    where=['%s.%s = %s.%s' % (table,join_column_2,rh_alias,join_column_1)])

添加附加列以供select dict使用。

Add additional columns to have available to the select dict.

附加约束在ON()之后放在WHERE中,其中您的SQL引擎可能优化很差。

The additional constraints are put together in a WHERE after the ON (), which your SQL engine may optimize poorly.

这篇关于自己加入django ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆