Many to many

Posted by WiseGuy on Tue, 22 Oct 2019 18:22:48 +0200

Create the third table to establish many to many relationship

Table creation

# The teacher table and student table can be a many to many relationship. When creating a table, you can manually create a third table to establish an association.

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

class Teacher(models.Model):
    name = models.CharField(max_length=32, null=True)
    gender = models.CharField(max_length=32, null=True)

# Create a third table, and associate the first two tables
class TeacherToStudent(models.Model):
    stu = models.ForeignKey('Student', null=True)
    teac = models.ForeignKey('Teacher', null=True)

Add, delete, modify and query

# Add directly through the model. Class name. objects.create
models.Student.objects.create(name="xxx",age=12)
models.Teacher.objects.create(name="ooo",gender="male")
models.TeacherToStudent.objects.create(stu_id=1, teac_id=1)

# Delete to find the object. delete(), and delete the corresponding relationship.
models.Teacher.objects.filter(id=4).delete()
models.TeacherToStudent.objects.filter(teac_id=4).delete()

# Change different tables to separate operations
models.Teacher.objects.filter(id=3).update(name="xoxo")

# Check, if I want to find out how many teachers a student is taught at the same time, there are three ways
# 1:
res = models.Student.objects.filter(id=2).all()   # Find out the qualified students first
for row in res:
    print(row.name)
    r = row.teachertostudent_set.all()  # (reverse query) indicates all the rows with student id 2 in the third table
    for i in r:
        # i.teac    # (positive check) indicates a column in the corresponding teacher table
        print(i.teac.name)   # Find out all the teachers whose student id is 2.

# 2: 
res = models.TeacherToStudent.objects.filter(stu__name="cao").all()
# All the lines corresponding to the student's name cao are found (Magic double underline)
for row in res:
    print(row.stu.name, row.teac.name)  # Find the corresponding relationship between students and teachers

# 3: 
res = models.TeacherToStudent.objects.filter(stu__name="li").values("teac__name")
# The QuerySet list found contains the dictionary
print(res)

Creating many to many relationships with methods in Django

Table creation

# Table creation, creating a many to many relationship between a class and a course
# Create a many to many relationship through the ManyToManyField in django, and place the field in either of the two columns.
class Classes(models.Model):
    name = models.CharField(max_length=32, null=True)
    course = models.ManyToManyField('Course')
    
class Course(models.Model):
    name = models.CharField(max_length=32, null=True)

Add, delete, modify and query

# Find the corresponding class or course object before adding
obj = models.Classes.objects.filter(id=4).first()
# After finding it, add it through course.add when creating the table. Put the course id in the list, break it and pass it in.
obj.course.add(1)   # Add one more
obj.course.add(*[2,3])    # Add more

# Delete to find the object. Delete the property name. clear() when creating the table to delete all
obj = models.Classes.objects.filter(id=4).first()
obj.course.clear()

# Reset(change),Also find the object through.set()Method,Put a list in it.
obj = models.Classes.objects.filter(id=3).first()
obj.course.set([1,2,3])

# For a table with ManyToManyField field in the model class
res = models.Classes.objects.all()  # Find out all the objects first
for row in res:
    print(row.name)
    for i in row.course.all():  # row.course.all() is all course objects corresponding to each class
        print(i.name)
#For tables without ManyToManyField fields in the model class
res = models.Course.objects.all()   # And find out all the objects first.
for row in res:
    print("===================")
    print(row.name)
    for i in row.classes_set.all(): # All classes corresponding to each subject
        print(i.name)

Note: it is possible to establish many to many relationships between the two methods. Consider which one to use according to the situation. If the relationship between tables is simple,

The third table does not need to add fields other than the two table IDS, which can be created with django, but if the table relationship is complex,

In addition, some other fields need to be added to the third table, which requires our custom many to many relationship.(

Create the third table manually), and you can customize the structure of the third table

Topics: PHP Django