Django-queryset join without foreignkey

馋奶兔 提交于 2019-12-09 05:18:48

问题


model.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

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.


回答1:


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.

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



回答2:


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))




回答3:


Could you do this with .extra? From 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.



来源:https://stackoverflow.com/questions/19590483/django-queryset-join-without-foreignkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!