django模型对应关系

模型对应关系

文档将对模型的对应关系一对一、一对多、多对多的关系进行实例分析介绍

  • 1:1 OneToOneFileld
  • 1:N ForeignKey
  • M:N ManyToManyField

模型

#创建班级表()
class Grade(models.Model):
    g_name = models.CharField(max_length=10)
  
    #表名(不设置表名默认是:应用名_类名,app_grade,数据库名自动小写没有大写)
    class Meta:
        db_table = 'grade'


#创建一个学生表(学生与班级是一对多)
class Student(models.Model):
    s_name = models.CharField(max_length=20,unique=True)
    s_age = models.IntegerField(default=16)
    s_sex = models.BooleanField(default=1)
    #学生表与班级是一对多
    g = models.ForeignKey(Grade,null=True)

    #表名
    class Meta:
        db_table = 'student'


#创建一个学生信息表(学生信息与学生是一对一)
class StudentInfo(models.Model):
    adderss = models.CharField(max_length=20,null=True)
    phone = models.IntegerField(null=True)
    #学生信息表与学生表一对一
    stu = models.OneToOneField(Student)

    #表名
    class Meta:
        db_table = 'StudentInfo'
       
        
#创建一个课程信息表(课程与学生是多对多)        
class Coures(models.Model):
    c_name = models.CharField(max_length=10)
    #课程表与学生表是多对多
    stu = models.ManyToManyField(Student)

    #表名
    class Meta:
        db_table = 'course'
  • 上面的代码我们创建了一对一、一对多、多对多,从以上的例子中出发去了解他们之间的关系
  • 建立好模型在对应的python环境下进行迁移生成数据库,并手动添加数据
  • 一对一即学生与学生信息
#在视图中添加学生数据
def addStu(request) :
    if request.method == 'GET':
        Student.objects.create(s_name='妲己', s_age=20, s_sex=False)
        return HttpResponse('创建成功')

#在视图中删除学生信息 
def delStu(request):
    if request.method == 'GET':
        stu = Student.objects.filter(id=13)
        stu.delete()
        return HttpResponse("删除成功")

#找到对应信息
def oneToOneStu(request):
    if request.method == 'GET':
        #在学生模型中找到学生对象
        stu = Student.objects.get(id=1)
        #通过学生对象找一对一关联表信息
        #使用学生对象.学生信息表名(小写)获得信息表对象
        stuinfo = stu.studentinfo
        return HttpResponse(stuinfo)
        
        #通过拓展表找学生信息
        stuinfo = StudentInfo.objects.get(phone=123232321)
        #使用学生信息表对象.学生信息表OneToOneField的字段名获得信息对应学生对
        stu = stuinfo.stu
        return HttpResponse(stuinfo)
        
#修改信息就是找到对应的信息直接通过点语法修改即可
def alteroneToOneStu(request)
    if request.method == 'GET' :
     #在学生模型中找到学生对象
        stu = Student.objects.get(id=1)
        #修改学生表中信息
        stu.s_name = '新的名字'
        #修改信息需要进行保存
        stuinfo.save()
        #修改这名学生的学生信息表中的信息
        stuinfo = stu.studentinfo
        stuinfo.adders = '新的地址'
        #修改信息需要进行保存
        stuinfo.save()
  • 一对多即学生与班级
def OneToManyStu(request):
    if request.method == 'GET':
        #查询id=1的学生的班级名称
        stu = Student.objects.get(id=1)
        #拿到学生对象.ForeignKey字段名获得对应的班级对象
        stug = stu.g
        gname = stug.g_name
        return HttpResponse([stug])
        
        #id为1的班级的所有学生(filter拿到的是列表)
        grade = Grade.objects.filter(id=1)[0]
        #在涉及到设定关系字段的一方时,调用方法时需要使用_set来调用
        stus = grade.student_set.all()

  • 多对多即学生与课程
#添加课程
def addCoure(request):
    if request.method == 'GET':
        courses = ['高数','计算机网络']
        for coure in courses:
            Coures.objects.create(c_name=coure)
            return HttpResponse('添加成功')


#给学生添加课程
def ManyToSelect(request):
    if request.method == 'GET':
        #拿到学生
        stu = Student.objects.get(id=1)
        #拿到课程c1
        c1 = Coures.objects.get(id=1)
        #拿到课程c2
        c2 = Coures.objects.get(id=2)
        #涉及了ManyToManyFiel在课程表中。为学生添加c1,c2时.课程要使用_set
        stu.coures_set.add(c1)
        stu.coures_set.add(c2)
  
  
        
#给课程添加学生
def ManyToSelect(request):
    if request.method == 'GET':
       #拿到学生
        stu = Student.objects.get(id=1)
        #拿到课程c1
        c1 = Coures.objects.get(c_name='计算机网络')
        #拿到课程c2
        c2 = Course.objects.get(c_name='数学')
        #给课程添加学生()
        c1.courses.add(stu)
        c2.courses.add(stu)
  • 总结
一对第一

class B():
	id = models.autoFiled(primary_key=True)

class A():
	b = models.OneToOneField(B)

有A的对象,查询B
a = A()
b= a.b
b_id = a.b_id

有B的对象,反查A

b = B()
a = b.a

4. 一对多

class B():
	id = models.autoFiled(primary_key=True)

class A():
	b = models.ForeignKey(B)

一对多和一对一的关系: 一对多中外键是唯一的,那就成了一对一


有A的对象,查询B
a = A()
b =a.b

有B的对象,反查A
b = B()
a = b.a_set.all()

5. 多对多

class B():
	id = models.autoFiled(primary_key=True)

class A():
	b = models.ManyToManyField(B)

生成的表有三张,A表,B表,A_B表(迁移数据库自动生成)


有A的对象,查询B
a = A()
b =a.b

有B的对象,反查A
b = B()
a = b.a_set.all()

插入数据
a = A.objects.get(pk=1)
b = B.objects.get(pk=1)
a.b.add(b)
b.a_set.add(a)

删除数据
b.a_set.remove(a)
  • 多对多练习
    • 模型
from django.db import models

# Create your models here.


class Author(models.Model):
    a_name = models.CharField(max_length=20)
    a_age = models.IntegerField(null=True)
    a_sex = models.BooleanField(default=True)
    a_address = models.CharField(max_length=20)

    class Meta:
        db_table = 'author'


class Book(models.Model):
    b_name = models.CharField(max_length=20)
    b_type = models.CharField(max_length=10)
    b_lenght = models.IntegerField(default=10000, null=True)
    author = models.ManyToManyField(Author)

    class Meta:
        db_table = 'book'

  • 视图
from django.shortcuts import render
from django.http import HttpResponse
from app2.models import Author
from app2.models import Book



def bookadd(request):
    if request.method == 'GET':
        # 创建书籍
        Book.objects.create(b_name='白夜追凶', b_type='悬疑', b_lenght=100000)
        Book.objects.create(b_name='斗罗大陆', b_type='玄幻', b_lenght=2000000)
        Book.objects.create(b_name='斗破苍穹', b_type='玄幻', b_lenght=2000000)
        Book.objects.create(b_name='盗墓笔记', b_type='悬疑', b_lenght=1500000)
        Book.objects.create(b_name='红楼梦', b_type='古典小说', b_lenght=1200000)
        return HttpResponse('创建书籍成功')


def authoradd(request):
    if request.method == 'GET':
        # 创建作者
        Author.objects.create(a_name='指纹', a_address='南京', a_age=43)
        Author.objects.create(a_name='唐家三少', a_address='北京', a_age=34)
        Author.objects.create(a_name='天蚕土豆', a_address='四川', a_age=31)
        Author.objects.create(a_name='南派三叔', a_address='浙江', a_age=45)
        Author.objects.create(a_name='曹雪芹', a_address='辽岭', a_age=48)
        Author.objects.create(a_name='高鹗', a_address='辽宁', a_age=57)
        return HttpResponse('创建作者成功')


def author_book_add(request):
    if request.method == 'GET':
        # 给书籍添加作者
        books = Book.objects.get(b_name='白夜追凶')
        authors = Author.objects.get(a_name='指纹')
        authors.book_set.add(books)
        books = Book.objects.get(b_name='斗罗大陆')
        authors = Author.objects.get(a_name='唐家三少')
        authors.book_set.add(books)
        books = Book.objects.get(b_name='斗破苍穹')
        authors = Author.objects.get(a_name='天蚕土豆')
        authors.book_set.add(books)
        books = Book.objects.get(b_name='盗墓笔记')
        authors = Author.objects.get(a_name='南派三叔')
        authors.book_set.add(books)
        books = Book.objects.get(b_name='红楼梦')
        authors = Author.objects.get(a_name='曹雪芹')
        authors.book_set.add(books)
        books = Book.objects.get(b_name='红楼梦')
        authors = Author.objects.get(a_name='高鹗')
        authors.book_set.add(books)
        return HttpResponse('给书籍添加作者成功')



def book_author_add(request):
    if request.method == 'GET':
        # 给书籍添加作者
        books = Book.objects.get(b_name='白夜追凶')
        authors = Author.objects.get(a_name='指纹')
        books.author.add(authors)
        books = Book.objects.get(b_name='斗罗大陆')
        authors = Author.objects.get(a_name='唐家三少')
        books.author.add(authors)
        books = Book.objects.get(b_name='斗破苍穹')
        authors = Author.objects.get(a_name='天蚕土豆')
        books.author.add(authors)
        books = Book.objects.get(b_name='盗墓笔记')
        authors = Author.objects.get(a_name='南派三叔')
        books.author.add(authors)
        books = Book.objects.get(b_name='红楼梦')
        authors = Author.objects.get(a_name='曹雪芹')
        books.author.add(authors)
        books = Book.objects.get(b_name='红楼梦')
        authors = Author.objects.get(a_name='高鹗')
        books.author.add(authors)
        return HttpResponse('给书籍添加作者成功')


def book_author_delete(request):
    if request.method == 'GET':
        # 删除书的作者
        books = Book.objects.get(b_name='红楼梦')
        author = Author.objects.get(a_name='高鹗')
        books.author.remove(author)
        return HttpResponse('删除书的作者')
        #删除作者的书
        author = Author.objects.get(a_name='南派三叔')
        books = Book.objects.get(b_name='盗墓笔记')
        author.book_set.remove(books)
        return HttpResponse('删除作者的书')


def bookdelete(request):
    if request.method == 'GET':
        books = Book.objects.get(b_name='红楼梦')
        books.delete()
        return HttpResponse('删除书')


def authordelete(request):
    if request.method == 'GET':
        author = Author.objects.get(a_name='南派三叔')
        author.delete()
        return HttpResponse('删除作者')


def book_author(request):
    if request.method == 'GET':
        #找到作者的书
        authon = Author.objects.get(a_name='高鹗')
        a = authon.book_set.all()
        #找到书的作者
        books = Book.objects.get(b_name='红楼梦')
        a = books.author.filter()
        return HttpResponse(a.values())

猜你喜欢

转载自blog.csdn.net/qq_32389821/article/details/82355373
今日推荐