程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django -- many to one relation of ORM table

編輯:Python
  • What is the many to one relationship

Django Use django.db.models.ForeignKey Define many to one relationships .

ForeignKey You need a positional parameter : The class associated with the model

 class Info(models.Model):
       user = models.ForeignKey(other_model,on_delete=models.SET_NULL)

Many to one relationships in life : Headmaster , Class relations . A head teacher can lead many classes , But each class can only have one head teacher

 from django.db import models
 # id name gender Define the teacher's model class
 class Teacher(models.Model):
     name = models.CharField(max_length=30,verbose_name=" Teacher name ")
     gender = models.CharField(max_length=10,verbose_name=" Teacher gender ")
     class Meta:
         db_table = "teachers"
     def __str__(self):
         return self.name
 # id name gender score teacher_id
 class Student(models.Model):
     name = models.CharField(max_length=20,verbose_name=" The student's name ")
     gender = models.CharField(max_length=10,verbose_name=" Student gender ")
     score = models.IntegerField(verbose_name=" Students' scores ")
     # to: Then write the associated model class  
     # on_delete=models.CASCADE: Delete data in the main table , Delete from table
     # Foreign keys are associated with the entire model class , Not a single object
     # But an associated field is generated through the model class Field name _id
     teacher = models.ForeignKey(to=Teacher,on_delete=models.CASCADE,verbose_name=" My teacher ")
     class Meta:
         db_table = "students"
     def __str__(self):
         return self.name
  • Adding, deleting, and modifying many to one relationships

  Add teacher grammar :
  Model class .objects.create()
     Teacher.objects.create(name=" Teacher wang ",gender=" Woman ")
  Delete teacher grammar :
  Model class .objects.get( Conditions ).delete()
  # Delete id by 2 Teacher
  Teacher.objects.get(id=2).delete()  # (3, {'myapp.Student': 2, 'myapp.Teacher': 1})
# 3 Represents the total number of data deleted Student Delete 3 strip Teacher Delete 1
  Revise the teacher's grammar :
      Model class .objects.filter( Conditions ).update()
  # modify id by 3 My teacher is female
  Teacher.objects.filter(id=3).update(gender=" Woman ")

The above created two pieces of teacher data   Because we set the foreign key association to be null null=True, So when the class table is created , It can be saved directly , No teacher data is required

  Add student grammar :
      Model class .objects.create()
  Through foreign keys _id In the form of
  Student.objects.create(name=" Li Si ",gender=" male ",score=80,teacher_id=3)
  Assign a teacher object directly to the foreign key
  t1 = Teacher.objects.create(name=" Miss li ",gender=" male ")
  Student.objects.create(name=" Li Si ",gender=" male ",score=80,teacher=t1)
  Delete student grammar :
  Model class .objects.get( Conditions ).delete()
     Student.objects.get(id=1).delete()
  Modify student grammar :
      Model class .objects.filter( Conditions ).update( Field 1, Field 2...)
     Student.objects.get(id=1).update(name=" Zhang San ")

Be careful Remember to get the data again after deleting , Otherwise, the class data with teachers obtained before is still in the viewed results

  • Many to one forward query

After assigning the teacher to a class , Because the class table is associated with the teacher field , We can find the corresponding teacher through the class   Although there is no associated class field in the teacher table ,

But you can also find his class through the teacher , This query method is also called Association query

 # Inquire about id by 2 The name of the teacher of the student 
  -- find id by 2 Of the students
     stu = Student.objects.get(id=2)
     -- find stu The corresponding teacher    stu.teacher.name
     stu. Foreign keys .name
  • Many to one reverse query

Add a after the model class name _set, To implement reverse query

  Reverse query : adopt django The built-in properties of   Model class ( Model class lowercase )_set() You can reverse query all the students under the teacher's name ,
     # Inquire about id by 1 All the students of the teacher   -- First find id by 1 Teacher    
     tea = Teacher.objects.get(id=1)    
     -- Inquire about tea All the students under the teacher's name   Teacher object . Model class _set.all()    
     tea.student_set.all()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved