Python 没有外键的 Django-queryset 连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19590483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:07:38  来源:igfitidea点击:

Django-queryset join without foreignkey

pythondjangodjango-queryset

提问by luzik

model.py

模型.py

class Tdzien(models.Model):
  dziens = models.SmallIntegerField(primary_key=True, db_column='DZIENS')
  dzienrok = models.SmallIntegerField(unique=True, db_column='ROK')


class Tnogahist(models.Model):
  id_noga = models.ForeignKey(Tenerg, primary_key=True, db_column='ID_ENERG')
  dziens = models.SmallIntegerField(db_column='DZIENS')

What I want is to get id_noga where dzienrok=1234. I know that dziens should be

我想要的是在 dzienrok=1234 处获得 id_noga。我知道 dziens 应该是

dziens = models.ForeignKey(Tdzien)

but it isn't and I can't change that. Normally I would use something like

但事实并非如此,我无法改变这一点。通常我会使用类似的东西

Tnogahist.objects.filter(dziens__dzienrok=1234)

but I don't know how to join and filter those tables without foreignkey.

但我不知道如何在没有外键的情况下加入和过滤这些表。

采纳答案by Lucas

It's possible to join two tables by performing a raw sql query. But for this case it's quite nasty, so I recommend you to rewrite your models.py.

可以通过执行原始 sql 查询来连接两个表。但是对于这种情况,它很讨厌,所以我建议你重写你的models.py。

You can check how to do this here

您可以在此处查看如何执行此操作

It would be something like this:

它会是这样的:

from django.db import connection

def my_custom_sql(self):
    cursor = connection.cursor()    
    cursor.execute("select id_noga
                    from myapp_Tnogahist a
                    inner join myapp_Tdzien b on a.dziens=b.dziens
                    where b.dzienrok = 1234")
    row = cursor.fetchone()
    return row

回答by RemcoGerlich

No joins without a foreign key as far as I know, but you could use two queries:

据我所知,没有外键就没有连接,但您可以使用两个查询:

Tnogahist.objects.filter(dziens__in=Tdzien.objects.filter(dzienrok=1234))

Tnogahist.objects.filter(dziens__in=Tdzien.objects.filter(dzienrok=1234))

回答by Paul Tomblin

Could you do this with .extra? From https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra:

你能做到这一点.extra吗?从https://docs.djangoproject.com/en/dev/ref/models/querysets/#extra

where / tables

You can define explicit SQL WHERE clauses — perhaps to perform non-explicit joins — by using where. You can manually add tables to the SQL FROM clause by using tables.

哪里/表

您可以使用 where 定义显式 SQL WHERE 子句——也许是为了执行非显式连接。您可以使用表手动向 SQL FROM 子句添加表。