Django之数据库联表查询,一对多,多对多

from django.db import models

# Create your models here.

"""
一对多: subject 和  学生
多对多: 老师,学生  

"""


class Subject(models.Model):
    name = models.CharField(max_length=32)
    price = models.IntegerField()

    def __str__(self):
        return '{}--{}'.format(self.name, self.price)


class Student(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    phone = models.CharField(max_length=32)
    
    #多对一在多的一方创建外键,外键生成后会自动添加_id
    subject = models.ForeignKey(to='Subject', on_delete=True)

    def __str__(self):
        return '{}-{}'.format(self.name, self.age)


class Teacher(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    phone = models.CharField(max_length=32)
    salary = models.CharField(max_length=32)
    
	#多对多,在任意类中创建均可
    student = models.ManyToManyField(to='Student')

    def __str__(self):
        return '{}-{}'.format(self.name, self.age)

from django.shortcuts import render
from app01 import models

Create your views here.

def index(request):
    # 一对多查询,subject --> 学生
    # # 正向查询
    # # 1.查询出盈利学的学科
    # student_obj = models.Student.objects.get(name='盈利')
    # print(student_obj)
    # sub_obj = student_obj.subject  # 查询出来的是学科对象
    # print(sub_obj)
    #
    # 2.查询出python学科对应的学生
    # 反向查询
    python_obj = models.Subject.objects.get(name='python')
    python_list = models.Subject.objects.filter(name='python') #查询出来的是QuerySet对象
    print(python_list)  # <QuerySet [<Subject: python--20800>]>
    python_obj = models.Subject.objects.filter(name='python')[0]
    print(python_obj)  # python--20800
    student_lst = python_obj.student_set.all()  # 固定写法:xx.类名小写_set.xxx
    print(student_lst) # <QuerySet [<Student: 盈利-21>, <Student: 谢老板-32>]>

    # 2.多对多
    # 查询 波老师教过的学生
    bo_obj = models.Teacher.objects.get(name='波老师')
    student_lst = bo_obj.student.all()
    print(student_lst)

    # 反向查询
    # 查询盈利被多少老师教过
    student_obj = models.Student.objects.get(name='盈利')
    teacher_lst = student_obj.teacher_set.all()
    print(teacher_lst)
    return render(request, 'app01/index.html', locals())

猜你喜欢

转载自blog.csdn.net/weixin_44183162/article/details/87991261