Python Day 59 Django framework, the many-table operation Django ORM

  ## Create a third table to establish themselves-many relationship

# Teachers and students table tables may be one-many relationship, you can create a third table associated manually when construction of the table 

class Student (models.Model): 
    name = models.CharField (= 32 max_length, null = True) 
    Age models.CharField = (= 32 MAX_LENGTH, null = True) 

class Teacher (models.Model): 
    name = models.CharField (= 32 MAX_LENGTH, null = True) 
    Gender = models.CharField (= 32 MAX_LENGTH, null = True) 

# the establishment of the third table, two tables together before the association 
class TeacherToStudent (models.Model): 
    STU = models.ForeignKey ( ' Student ' , null = True) 
    TEAC = models.ForeignKey (' Teacher ' , null = True)
     class Meta -:
     # United unique index 
        unique_together = [ 
            ( ' STU ' , ' TEAC ' ),             
    ]

   ## CRUD operations

# Increase directly by models. .Objects.create class name added 
models.Student.objects.create (name = " xxx " , Age = 12 ) 
models.Teacher.objects.create (name = " OOO " , Gender = " M " ) 
models.TeacherToStudent.objects.create (stu_id =. 1, teac_id =. 1 ) 

# puncturing identify objects .delete (), and delete the correspondence relationship 
models.Teacher.objects.filter (= ID. 4 ) .Delete ( ) 
models.TeacherToStudent.objects.filter (teac_id =. 4 ) .Delete () 

# change as different tables operated separately 
models.Teacher.objects.filter (= ID. 3) .Update (name = " XOXO " )

# Check, if I am asking for a student to be taught at the same time the number of teachers, there are three ways to chart at 
# 1: 
RES = models.Student.objects.filter (the above mentioned id = 2) .all ()    # to identify eligible students 
for row in RES:
     Print (row.name) 
    r = row.teachertostudent_set.all ()   # (reverse lookup) tables represent a third of all students with id 2 rows 
    for i in r:
         # i.teac # (n check ) indicates that the corresponding table of a teacher 
        Print (i.teac.name)    # detect student id 2 corresponds to all teachers 

# 2: 
RES = models.TeacherToStudent.objects.filter (stu__name = " CaO " ) .all ( )
 # check out the names of the students for all rows (magical double underline) cao corresponding
for Row in RES:
     Print (row.stu.name, row.teac.name)   # find correspondence between students and teachers 

# 3: 
RES = models.TeacherToStudent.objects.filter (stu__name = " li " ) .values ( " teac__name " )
 # check out QuerySet list, which contains the dictionary 
Print (RES)

 

Guess you like

Origin www.cnblogs.com/liangzhenghong/p/11202207.html