Django ORM连接没有外键也没有原始查询 [英] Django ORM join without foreign keys and without raw queries

查看:485
本文介绍了Django ORM连接没有外键也没有原始查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class AKeywords(models.Model):
    id = models.AutoField(primary_key=True, db_column="kw_id")
    word = models.CharField(max_length=200)
    ...

    class Meta:
        managed = False
        db_table = '"A"."Keywords"'

B

class BKeywords(models.Model):
    id = models.AutoField(primary_key=True, db_column="kw_id")
    word = models.CharField(max_length=200)
    ...
    class Meta:
        managed = False
        db_table = '"B"."Keywords"'

我还有一个模型,我想执行我的加入.

I have another model where i would like to perform my join.

class XKeywords(models.Model):
    ...
    k_id = models.IntegerField(blank=True, null=True)
    ...

    class Meta:
        managed = False
        db_table = '"public"."XKeywords"'

我有两个非常相似的模型,一个来自数据库模式,另一个来自另一个数据库模式. 我想要第三个将与表A或B连接的模型.

I have two models that are very similar, one comes from a database schema and another from another database schema. A third model that will be to join with table A or B has i want.

如何在不使用外键和原始查询的情况下加入模型A或B?

How can i join model A or B without using foreignkeys and raw queries?

推荐答案

这将起作用:

XKeywords.objects.filter(pk_id=my_id).extra(select={'word':'SELECT word FROM "A"."Keywords" WHERE "public"."XKeywords".k_id = "A"."Keywords".kw_id'})

raw_sql = """SELECT * FROM (SELECT * FROM "public"."XKeywords" WHERE pk_id = my_id) as "XK" LEFT OUTER JOIN  "A"."Keywords" as "AK" ON "AK".kw_id = "XK".k_id ;"""
XKeywords.objects.raw(raw_sql)

这是一种解决方法,我期待有更多聪明"的东西.拥有更直接的类似东西会很好:

This is an workaround i was expecting something more "clever". It would be nice to have something more directly like:

XKeywords.objects.filter(pk_id=my_id).join(k_id=A.kwd,from={"AKeywords":"A"})

这篇关于Django ORM连接没有外键也没有原始查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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