Django的模拟SQL“INNER DJOIN”

时间:2017-05-27 03:49:15

标签: python sql django

#models.py
#
class Students(models.Model):
    StudentID = models.IntegerField(primary_key=True)
    FIO = models.CharField(max_length=50)
    StudGroup = models.CharField(max_length=10)
    NYear = models.IntegerField()

class Phone(models.Model):
    Code = models.AutoField(primary_key=True)
    StudentID = models.ForeignKey(Students)
    Phone = models.BigIntegerField()


#views.py
#
def show_all(reqest):
all_students = Students.objects.all()
return render_to_response('demosite/index.html', 
        {'All_students': all_students})

此代码正常运行。

现在我的视图返回此请求:

SELECT * FROM Students

但是变量all_students应该包含来自2个表的数据。

如何让django运行此请求:

SELECT Students.FIO, Phone.Phone FROM Students INNER DJOIN Phone ON Students.StudentID = Phone.StudentID 

1 个答案:

答案 0 :(得分:0)

你需要学生FIO和Phone.Phone学生,

你可以这样做,

Phone.objects.values('Phone', 'StudentID__FIO')