我还在学习Django。任何熟悉Django 1.8或更高版本的人都可以帮助我解决这个问题。我在加入这5个表时遇到问题,我想执行一个等同于这个SQL查询的查询:
SELECT *
from modelname1 a
join modelname2 b on a.id = b.id
join modelname3 c on c.id = b.id
join modelname4 d on d.id = c.id
join modelname5 on e.id = d.id;
我有这些模特:
class modelname1(models.Model):
modelname1_id = models.AutoField(primary_key = True)
a = models.CharField(max_length = 200)
b = models.CharField(max_length = 200)
class modelname2(models.Model):
modelname2_id = models.AutoField(primary_key = True)
a = models.CharField(max_length = 200)
b = models.CharField(max_length = 200)
c = models.ForeignKey(modelname1)
class modelname3(models.Model):
modelname3_id = models.AutoField(primary_key = True)
a = models.CharField(max_length = 200)
b = models.CharField(max_length = 200)
c = models.ForeignKey(modelname2)
class modelname4(models.Model):
modelname4_id = models.AutoField(primary_key = True)
a = models.CharField(max_length = 200)
b = models.CharField(max_length = 200)
c = models.ForeignKey(modelname3)
class modelname5(models.Model):
modelname5_id = models.AutoField(primary_key = True)
a = models.CharField(max_length = 200)
b = models.CharField(max_length = 200)
c = models.ForeignKey(modelname4)
我不知道如何在Django中翻译我想要的查询, 我可以使查询产生相同的答案,但我需要在得到相同答案之前将其分成多个查询。 非常感谢您的帮助!
答案 0 :(得分:0)
在Django中你可以像这样查询:
>>>from app.models import modelname1
>>> q = modelname1.objects.get(id = 1)
>>> m2 = q.modelname2 # In django 1.8 or later
>>> m3 = m2.modelname3
>>> m4 = m3.modelname4
... And so on!
但由于大量的数据库命中,我不能提供这种方式。如果要优化数据库访问可以阅读本文: https://docs.djangoproject.com/en/1.9/topics/db/optimization/