创建模型
from django.db import models #学生类 class Student(models.Model): id = models.AutoField(primary_key=True) sname = models.CharField(max_length=20) # 一对多外键设置,'多'的模型类设置外键,注意需要带参数on_delete cid = models.ForeignKey('Class',on_delete=models.CASCADE) # 一对一外键设置,哪个模型设置外键都可以,注意需要带参数on_delete detail = models.OneToOneField('StudentDetail',on_delete=models.CASCADE) #学生信息类 class StudentDetail(models.Model): id = models.AutoField(primary_key=True) height = models.IntegerField() email = models.EmailField() memo = models.TextField(max_length=100) #班级类 class Class(models.Model): id = models.AutoField(primary_key=True) cname = models.CharField(max_length=20) cdata = models.DateField() #老师类 class Teacher(models.Model): id = models.AutoField(primary_key=True) tname = models.CharField(max_length=20) #多对多外键设置,哪个模型类创建外键都可以,注意没有on_delete参数 cid = models.ManyToManyField(Class)
在mysql数据库中生成对应表格
#创建迁移文件 python manage.py makemigrations #应用迁移文件 python manage.py migrate
操作
一对一
Student ---> StudentDetail #正向 Student.objects.filter(id__gt=2)[0].detail StudentDetail.objects.filter(student__id__gt=1) #反向 StudentDetail.objects.get(id=1).student Student.objects.filter(detail__id__exact=1)
一对多
Student ---> Class add(obj1, obj2, ...)添加一指定的模型对象到关联的对象集中 create(**kwargs)创建一个新的对象,将它保存并放在关联的对象集中。返回新创建的对象 remove(obj1, obj2, ...)从关联的对象集中删除指定的模型对象 clear()从关联的对象集中删除所有的对象。 Student ---> Class s1=Student(**data) s1.save() c1 =Class(**data1) c1.save() c1.student_set.add(s1) c1.student_set.create(**data) a1 = Student.objects.filter(id=1) c1.student_set.remove(a1) c1.article_set.clear() #正向 Student.objects.get(id=1).cid Class.objects.filter(student__id=1) #反向 Class.objects.get(id=1).student_set.all() #副表调用主表信息,使用 主表名(全小写)__set Student.objects.filter(cid__id=1)
多对多
Teacher --> Class # 正向 Teacher.objects.get(id=1).cid.all() Class.objects.filter(teacher__id=1) # 添加 Teacher.objects.get(id=5).cid.add(*Class.objects.filter(id__gt = 3)) #移除 Teacher.objects.get(id=5).cid.remove(*Class.objects.filter(id__gt=1)) #清空对象关系 Teacher.objects.get(id=5).cid.clear() #重新设置关系 #添加新关系,删除多余关系 Teacher.objects.get(id=5).cid.set(list(Class.objects.filter(id__gt=5)) )#参数为一个可迭代对象就可以 #反向 Class.objects.get(id=1).teacher_set.all() Teacher.objects.filter(Q(cid__id=1) | ~Q(cid__id=2))
标签:__,Class,objects,一对一,Django,filter,models,ORM,id From: https://www.cnblogs.com/boye169/p/17637228.html