如何在Django 1.11中进行加入声明, 我想创建此语句:
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()
...
我尝试过
t1 = t1.objects.filter(**params).exclude(**exclude)
t1 = t1.select_related('t2')
`
但是我可以在哪里添加on语句?
注意-联接不是通过外键
答案 0 :(得分:1)
不,不幸的是,没有一种有效/优雅的方法。
尽管您可以使用.raw()/RawSQL()
方法执行此操作。即使可能,它也可能比原始SQL慢很多。
https://docs.djangoproject.com/en/2.2/topics/db/sql/
答案 1 :(得分:0)
您不应添加on
语句。 Django的 ORM将自动为您执行内部联接。
class User(models.Model):
name = models.CharField(max_length=30)
surname = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=50)
text = models.TextField()
user = models.ForeignKey(to='User', on_delete=models.CASCADE) # this is FK field to users
qs = Post.objects.select_related('user') # This will performs SQL INNER JOIN.
print(qs.query) # use query attribute to show what query is performed.
这将生成SQL查询
SELECT "myapp_post"."id", "myapp_post"."title", "myapp_post"."text", "myapp_post"."user_id", "myapp_user"."id", "myapp_user"."name", "myapp_user"."surname" FROM "myapp_post" INNER JOIN "myapp_user" ON ("myapp_post"."user_id" = "myapp_user"."id")
查看您的模型,
class t1(UTModelTS):
alt_keys = product_alt_keys
name = utCharField()
t2 = models.ForeignKey(to='t2', on_delete=models.CASCADE)
class t2(UTModelTS):
alt_keys= [('pr_id', 'section')]
str = utCharField()
num = models.IntegerField()
将t2 FK添加到您的t1模型中。
查询
qs = t1.objects.select_related('t2')
qs = t1.objects.select_related('t2').filter(**lookup_kwargs).
select_related()
返回QuerySet
对象,您可以在QuerySet
之后使用select_related()
方法。