Django orm模型增删改查

1.模型创建与增删改查

from django.db import models

class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
    age = models.IntegerField()
    # to后面加类名 to_field后面写类名中的字段名   这是一对一的外键写法
    def __str__(self):
        return self.name
    class Meta:
        db_table = 'authors'

class AuthorDetail(models.Model):
    id = models.AutoField(primary_key=True)
    addr = models.CharField(max_length=16)
    author = models.OneToOneField(Author,on_delete=models.CASCADE)
    class Meta:
        db_table = 'authordetil'

class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
    addr = models.CharField(max_length=16)
    class Meta:
        db_table = 'publish'

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16)
    price = models.DecimalField(max_digits=6,decimal_places=2)
    # 在Book上publish变成了publish_id   这是一对多的外键写法
    publish = models.ForeignKey(Publish,on_delete=models.CASCADE)
    #  这个authors不是字段,他只是Book类里面的一个属性  这是多对多的建立第三张表的写法
    authors = models.ManyToManyField(Author,related_name='bookauthors')
    class Meta:
        db_table = 'book'
# 模型的增删改查
  常用的查询方法:
  魔法查询:
            后面跟双下划线"__",表示特殊查询常用的双下划线魔法参数有:
		 __year     __month   __day   __startswith  __endswith    __gte  __lte  __gt  __lt  __contains (相当于模糊查询)
		1. 名字中以"郭"开头的学生记录
		  students = Student.objects.filter(name__startswith='郭')
		2.名字中包含"郭"的学生记录
		  students = Student.objects.filter(name__contains='郭')
		3. 查询成绩大于等于85分的学生记录
		   students = Student.objects.filter(score__gte=85)
 Q查询:
               from django.db.models import Q
				1.使用Q查询男生中90分以上的学生记录
				 q1 = Q(sex='男')
				 q2 = Q(score__gte=90)
				students = Student.objects.filter(q1&q2)
				2. 使用Q查询姓“郭”或者成绩大于等于90分的学生记录
				q1 = Q(name__startswith='郭')
				q2 = Q(score__gte=90)
				students = Student.objects.filter(q1|q2)
				3.使用Q查询名字中不包含“郭”的学生
				 q = Q(name__contains='郭')
				 students = Student.objects.filter(~q)
F查询:
	使用F对象更新学生成绩,将某个学生的成绩在原有基础上(数据库层级)加5分
		stu = Student.objects.get(id=6)
		stu.score = F("score") + 5
		stu.save()
		>>> from django.db.models import Q
		>>> q1 = Q(price__gte=60)
		>>> q2 = Q(price__lte=40)
		>>> books = Book.objects.filter(q1|q2)
		>>>books.update(price=F("price")+100)
                     聚合查询:	可能要导入的:from django.db.models import Min,Avg,Max,Sum,Count
                     					1.查询所有学生的平均成绩:
		avg_score = Student.objects.all().aggregate(Avg("score"))
		结果是一个字典
		还可以自定义结果字典的key:
		avg_score = Student.objects.all().aggregate(avgscore=Avg("score"))
		2.查询班级成绩最高的学生成绩
		max_score = Student.objects.all().aggregate(scoremax=Max("score"))
		或者:
		max_score = Student.objects.aggregate(scoremax=Max("score"))
                    分组查询:
                      					根据性别分组,查询男女生的平均成绩
		students = Student.objects.values('sex').annotate(Avg('score'))
		
  排序查询  模型类名.objects.order_by("排序字段名")        
  排除查询  模型类名.objects.exclude(查询条件)                
  原生查询   模型类名.objects.raw("原生SQL")                   
 Author 表的添加新用户:① Author.objects.create(name="liuqi",age=18)
                     ② a = Author(name='liuqi',age=18)    a.save()
   删除用户:   Author.objects.get(id=1).delete()
   修改用户:   Author.objects.filter(id=1).update(age=25)  Quaryset 的update方法
   查询用户:  Author.objects.all()
                        Author.objects.filter().values("name") 返回QuerySet容器对象,其中的元素以字典格式表示
                        Author.objects.filter().values_list("name")  返回QuerySet容器对象,其中的元素以元组格式表示
  一对一查询
            对象间关联:
                       a1=Author.objects.get(id=1)
                        AuthorDetail.objects.create(addr="**",author=a1)
                       AuthorDetail.objects.create(addr="**",author_id=a1.id)
            ①从不维护关系的一方查询:使用另一方模型类名的小写
               查询id=1的作者 的地址
                     a1 = Author.objects.get(id=1) 
                     a1.authordetail.addr
            ② 从维护关系的一方查询 
               查询 1号楼的作者名字
              addr1 = AuthorDetail.objects.filiter(name='1号楼')
                     addr1.authors.name
 一对多查询
	        ① 一查多
                     一方的实例化对象.多方模型类名小写_set.all();
                      p1 = Publish.objects.get(id=1)
                      p1.book_set.all()
	         ② 多查一
                      b1 = Book.objects.get(id=1)
                      b1.publish
多对多查询:
           添加  a1 = Author.objects.get(id=1)
                        b1 = Book.objects.get(id=1)
                     a1.bookauthors.add(b1)
                     b1.authors.add(a1)
           删除    a1.bookauthors.remove(b1)
                      b1.authors.remove(a1)
           与其所有成员解除关系:
                       a1.bookauthors.clear()
        查询
               从维护关系的一方查询: 实例化对象.通过关联的类属性.all()
	                   b1 = Book.objects.get(id=1)
	                    b1.authors.all()
               从不负责维护关系的"多"方查询 :实例化对象.对方模型类名小写_set.all()
                      a1 = Author.objects.get(id=1)
                         a1.book_set.all() 或者 有related_name a1.bookauthors.all()
    三个模型实现多对多:
			     	from django.db import models

				class Member(models.Model):   # 成员模型
				    name = models.CharField(max_length=20)
				    age = models.IntegerField()
				    sex = models.CharField(max_length=10)
				    def __str__(self):
				        return self.name
				
				class Community(models.Model):  # 社团模型
				    name = models.CharField(max_length=20)
				    buildtime = models.DateField()
				    members = models.ManyToManyField(Member,through="Relation")
				
				    def __str__(self):
				        return self.name
				
				class Relation(models.Model):
				    member = models.ForeignKey(Member,on_delete=models.CASCADE)
				    community = models.ForeignKey(Community,on_delete=models.CASCADE)
				    join_reason = models.CharField(max_length=100)

模型外键自关联:
           一: 一对一自引用  (models.OneToOneField('self',on_delete=models.CASCADE,null=True)from django.db import models
				 class Spy(models.Model):
				    name = models.CharField(max_length=20)
				    age = models.IntegerField()
				    sex = models.CharField(max_length=10)
				    manager = models.OneToOneField('self',on_delete=models.CASCADE,null=True)
				    class Meta:
				    	 db_table = 'spies'
				
							创建Spy对象boss,并创建其他对象
							boss = Spy.objects.create(name='戴笠',age=45,sex='男')							
							spy1 = Spy.objects.create(name='毛人凤',age=30,sex='男',manager=boss)		
							spy2 = Spy.objects.create(name='张三',age=25,sex='男',manager=spy1)							
							查询boss的直属下属的名字:
							boss.spy.name 
				
           二 :一对多自引用:models.ForeignKey('self',on_delete=models.CASCADE,null=True)
		        from django.db import models
				class Emp(models.Model):
				    name = models.CharField(max_length=20)
				    age = models.IntegerField()
				    sex = models.CharField(max_length=10)
				    salary = models.FloatField()
				    manager = models.ForeignKey('self',on_delete=models.CASCADE,null=True)   # 外键自引用
				
				创建最高领导boss和其他员工:
				boss = Emp.objects.create(name='马云',age=55,sex='男',salary=3000.5)
				emp1 = Emp.objects.create(name='马晓云',age=25,sex='男',salary=2000,manager=boss)
				emp2 = Emp.objects.create(name='张勇',age=58,sex='男',salary=6000,manager=boss)
				emp3 = Emp.objects.create(name='张三',age=58,sex='男',salary=3000,manager=emp2)
				emp4 = Emp.objects.create(name='张丽',age=28,sex='女',salary=3000,manager=emp3)
				emp5 = Emp.objects.create(name='张小勇',age=22,sex='男',salary=3000,manager=emp2)
				
				查询id3的员工的直接下属与直属上司:
				emp = Emp.objects.get(id=3)
				workers = emp.emp_set.all()  # 直属下属
				leader = emp.manager
				
				级联删除所有员工:
				boss.delete()
       三:多对多自引用
	          from django.db import models
	                             
			class WeiUser(models.Model):
			    username = models.CharField(max_length=20)
			
			class WeiRelation(models.Model):
			    # 关联"被关注者"
			    followed = models.ForeignKey(WeiUser,on_delete=models.CASCADE,related_name="followed_relations")
			    # 关联"粉丝"
			    fans = models.ForeignKey(WeiUser,on_delete=models.CASCADE,related_name="fans_relations")
			
			添加用户:
			u1 = WeiUser.objects.create(username='二狗')
			u2 = WeiUser.objects.create(username='张学友')
			u3 = WeiUser.objects.create(username='小芳')
			u4 = WeiUser.objects.create(username='小刚')
			u5 = WeiUser.objects.create(username='翠花')
			
			建立关系:
			r1 = WeiRelation.objects.create(fans=u1,followed=u2)
			r2 = WeiRelation.objects.create(fans_id=1,followed_id=3)
			r3 = WeiRelation.objects.create(fans=u4,followed=u3)
			r4 = WeiRelation.objects.create(fans=u4,followed=u5)
			r5 = WeiRelation.objects.create(fans=u5,followed=u4)
			
			查询4号用户关注了哪些用户?
			user = WeiUser.objects.get(pk=4)
			relations = user.fans_relations.all()
			for r in relations:
			     print(r.followed.username)
			
			查询谁是4号用户的粉丝?
			user = WeiUser.objects.get(pk=4)
			relations = user.followed_relations.all()
			>>> for r in relations:
			             print(r.fans.username)
			
			4号用户取消对3号用户的关注
			 r = WeiRelation.objects.filter(fans_id=4,followed_id=3).first()
			r.delete()

                          
            
     

你可能感兴趣的:(orm,数据库,django,python)