如何在Django(ORM)中联接3个或更多表并获取结果?
已创建3个模型:
1.student 2.标记 3.细节
class Student:
s_id = models.IntegerField(primary_key=True)
s_name = models.CharField(max_length=100)
class Marks:
school_id = models.IntegerField(primary_key=True)
s_id = models.ForeignKey(Student, on_delete=models.CASCADE)
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
school_id = models.ForeignKey(Marks,on_delete=models.CASCADE)
accomplishments = models.TextField()
我需要加入这3个表并获取学生的姓名,得分,状态,地址城市,电子邮件ID,成就。
在SQL中,我们可以这样写:
select s_name, score, status, address_city, email_id,
accomplishments from student s inner join marks m on
s.s_id = m.s_id inner join details d on
d.school_id = m.school_id;
请让我知道如何使用DJANGO代码实现相同的目的。
答案 0 :(得分:0)
对给定型号的一些建议:
models.py:
class Student:
name = models.CharField(max_length=100)
class Marks:
student = models.ForeignKey(Student, on_delete=models.CASCADE)
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
school = models.ForeignKey(Marks,on_delete=models.CASCADE)
accomplishments = models.TextField()
现在,当我们在sql中创建映射表时,创建映射模型:
class StundetMarksDetailsMap:
student = models.ForeignKey(Student, on_delete=models.CASCADE)
marks = models.ForeignKey(Marks, on_delete=models.CASCADE)
details = models.ForeignKey(Details, on_delete=models.CASCADE)
现在,您可以根据需要在views.py或所需位置创建自己的queryset
:
class StudentView(generic.DetailsView):
model = Student
template = student_details.html
//this will return all values related student
def get_queryset(self):
return StundetMarksDetailsMap.objects.filter(student=Student)
基本上,此get_queryset
返回与所选择的stundet相关的模型对象,使用返回的Details和Marks对象在模板中调用它们的相应字段。还请仅使用要显示的字段。
希望这对您也有用。最好的:)
答案 1 :(得分:0)
我认为您应该使它保持简单,而不是使模型复杂化,当您拥有大量数据时,这种模型就不好了。将学生模型作为主要班级。并将所有其他信息存储在其他表中。
class Student:
name = models.CharField(max_length=100)
marks = models.ForeignKey(Marks,on_delete=models.CASCADE)
school = models.ForeignKey(School,on_delete=models.CASCADE)
class Marks:
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
accomplishments = models.TextField()
class School:
name = models.CharField(max_length=30)
details = models.ForeignKey(Details)
现在执行以下查询
student = Student.objects.filter(pk=student_id).filter(school_pk=school_id)
print student.name
print student.marks.score
print student.marks.status
print student.details.address_city
对于您当前的模型,很难查询。但是您可以尝试编写SQL查询本身。像这样
Blog.objects.extra(
select={
'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
},
)
关注此 https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra