django02

作者: 水果坚果燕麦片 | 来源:发表于2019-03-19 17:59 被阅读0次

    模型操作

    ① 在models.py中建立数据库模型

    class StudentInfo(models.Model):
      address = models.CharField(max_length=50, null=True)
      phone = models.CharField(max_length=11, null=True)
      
      class Meta:
        db_table = 'stu_info'
    
    class Grade(models.Model):
        g_name = models.CharField(max_length=100, null=True)
    
       class Meta:
         db_table = 'grade'
    
    class Student(models.Model):
      s_name = models.CharField(max_length=10, unique=True, null=False)
      age = models.IntegerField(default=18)
       # 第一次创建数据时,自动默认为当前创建的时间
      create_time = models.DateTimeField(auto_now_add=True)
       # 修改时自动更新为修改的时间
      operate_time = models.DateTimeField(auto_now=True)
      is_delete = models.BooleanField(default=0)
      chinese = models.DecimalField(max_digits=3, decimal_places=1,null=True)
      math = models.DecimalField(max_digits=3, decimal_places=1,null=True)
      # 一对一字段,一个学生对应一条学生信息
      stuinfo = models.OneToOneField(StudentInfo, related_name='stu', on_delete=models.CASCADE, null=True)  
      # 多对多字段,
      grade = models.ForeignKey(Grade,related_name='stu',on_delete=models.CASCADE, null=True)
      class Meta:
        db_table = 'student'
    

    views.py中通过学生信息表查找学生信息

    def sel_stu_by_info(request):
      if request.method == 'GET':
        stuinfo = StudentInfo.objects.filter(phone = '123456').first()
    # 通过django自带的OneToOneField即可通过related_name自动创建外键关系
        stu = stuinfo.stu
      return HttpResponse('查询成功')
    
    def add_grade(request):
        if request.method == 'GET':
            names = ['python班级', 'Java班级', 'Php班级', 'C++班级']
            for name in names:
                if not Grade.objects.filter(g_name=name).exists():
                    Grade.objects.create(g_name=name)
            # 分配班级
            stus = Student.objects.filter(pk__in=[1, 2, 3, 4, 5]).all()
            g = Grade.objects.filter(g_name='python班级').first()
            for stu in stus:
                stu.grade = g
                #stu.grade_id = g.id
                stu.save()
            return HttpResponse('添加班级和学生信息')
    

    相关文章

      网友评论

          本文标题:django02

          本文链接:https://www.haomeiwen.com/subject/fkjnmqtx.html