model.py
JavaScript
x
9
1
class Tdzien(models.Model):
2
dziens = models.SmallIntegerField(primary_key=True, db_column='DZIENS')
3
dzienrok = models.SmallIntegerField(unique=True, db_column='ROK')
4
5
6
class Tnogahist(models.Model):
7
id_noga = models.ForeignKey(Tenerg, primary_key=True, db_column='ID_ENERG')
8
dziens = models.SmallIntegerField(db_column='DZIENS')
9
What I want is to get id_noga where dzienrok=1234. I know that dziens should be
JavaScript
1
2
1
dziens = models.ForeignKey(Tdzien)
2
but it isn’t and I can’t change that. Normally I would use something like
JavaScript
1
2
1
Tnogahist.objects.filter(dziens__dzienrok=1234)
2
but I don’t know how to join and filter those tables without foreignkey.
Advertisement
Answer
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:
JavaScript
1
11
11
1
from django.db import connection
2
3
def my_custom_sql(self):
4
cursor = connection.cursor()
5
cursor.execute("select id_noga
6
from myapp_Tnogahist a
7
inner join myapp_Tdzien b on a.dziens=b.dziens
8
where b.dzienrok = 1234")
9
row = cursor.fetchone()
10
return row
11