Ad

How To Make An Inner Join In Django Without Foreign Key?

- 1 answer

how to make statement of join on in django 1.11, i want to create this statement :

select t1.name ,t2.str, t2.num
from table_1 as t1
join table_2 as t2 on t2.product_id = t1.id and t2.section_num = 2;

the models:


class t1(UTModelTS):
    alt_keys = product_alt_keys
    name = utCharField()
    ...

class t2(UTModelTS):
    alt_keys= [('pr_id', 'section')]    
    str = utCharField()
    num = models.IntegerField()

    ...

i tried

 t1 = t1.objects.filter(**params).exclude(**exclude)
 t1 = t1.select_related('t2')
`

but this make no sense since acoridng to django doc : select_related Returns a QuerySet that will “follow” foreign-key relationships... from https://docs.djangoproject.com/en/2.2/ref/models/querysets/ .

Ad

Answer

No, there isn't an effective / elegant way unfortunately.

although you can use .raw()/RawSQL() method for this exact thing. Even if it could it probably would be a lot slower than raw SQL. https://docs.djangoproject.com/en/2.2/topics/db/sql/

Ad
source: stackoverflow.com
Ad