Establishment of django Data Relation One to many Many to many Model and Self correlation

  • 2021-07-26 08:10:52
  • OfStack

1-to-many model

1-to-many relationships, such as employees and departments. One department has multiple employees. So how do you establish this table relationship in django?

In fact, it is to use foreign keys. In one more side, the field can specify foreign keys. For example, employees and departments, there are many employees, so direct departments in the employee table can be used.

Example (see line 19):


class Department(models.Model):
  name = models.CharField(max_length=20)
  create_data = models.DateField(auto_now_add=True)
  is_delete = models.BooleanField(default=False)

  class Meta:
    db_table = "department"


class Employee(models.Model):
  name = models.CharField(max_length=20)
  age = models.IntegerField()
  gender = models.IntegerField(default=0)
  # decimal_place = 2 Represents two decimal places, max_digits Denote 8 Numbers, including two decimal places 
  salary = models.DecimalField(max_digits=8,decimal_places=2)
  # null=True  Indicates that it can be null ,blank=True Denote django Background management input this field can be blank 
  comment = models.CharField(max_length=300,null=True,blank=True)
  hire_data = models.DateField(auto_now_add=True)
  department = models.ForeignKey("Department")

  class Meta:
    db_table = "employee"

Expand:

1. When setting foreign keys, it is necessary to indicate how to handle foreign key reference table data when deleting data from the main table through on_delete option. Optional constants are included in django. db. models:

Value of on_delete option for associated attribute

models. CASCADE This is the default value. Cascade deletion will delete the associated data

department = models.ForeignKey('Department', on_delete=models.CASCADE)
models. PROTECT cannot be deleted as long as there is associated data

department = models.ForeignKey('Department', on_delete=models.PROTECT)
models. SET_NULL After data is deleted, the associated field is set to NULL, available only if the field is allowed to be null (null=True)

2. If the associated field is not in model. py of the application folder, write it like this


department = models.ForeignKey("( Application folder name ).Department")

There is another one that needs special attention:

department = models.ForeignKey("Department",related_name='employee') employee is used to find employees by department. If not set, the default employee_set (lowercase for class name +_set) is used

1-to-many queries:

The department to which an employee belongs (what is found out is the object):


a = Employee.objects.get(id=1)
b = a.department

All employees in 1 department (what is found out is the object):


a = Department.objects.get(id=1)
b = a.employee_set.all()

Many-to-many model

Many-to-many relationships, such as students and associations. One student can enter multiple clubs, and one club can have multiple students. So how to establish this table relationship in django?

django There are two ways to establish many-to-many relationships.

Method 1:


class Student(models.Model):
  name= models.CharField(max_length=16)
  birthday=models.DateField()
class Club(models.Model):
  name= models.CharField(max_length=16)
  members = models.ManyToManyField("Student")

Just add ManyToManyField similar to line 6 to any one side. Django automatically creates one table for a many-to-many association for the connection of two tables.

What about queries?

1.1 All members of the community (the target is found out)


c = Club.objects.get(id=1)
c.members.all()

2.1 All Societies of Members (Objects Found)


s = Student.objects.filter(id=1)
s.club_set.all() #  Lowercase of class name +_set

Method 2: (more flexible)

Manually establish a table association by yourself.


class Student(models.Model):
  name= models.CharField(max_length=16)
  birthday=models.DateField()

class Club(models.Model):
  name= models.CharField(max_length=16)

class Membership(models.Model):
  student = models.ForeignKey("Student")
  club = models.ForeignKey("Club")

So how to query the table in this way?

All clubs that 1 student joins:


department = models.ForeignKey('Department', on_delete=models.CASCADE)
0

All students of a club:


department = models.ForeignKey('Department', on_delete=models.CASCADE)
1

Autocorrelation model

The self-association model is that one column in a table is associated with another column in this table. The most typical self-association model is the region table. Provinces, cities and counties are all in one table. pid of province is null, pid of city is id of province and pid of county is id of city.

Example:


department = models.ForeignKey('Department', on_delete=models.CASCADE)
2

So, how to inquire?

If you know a city called a, you want to find out what province it belongs to.


a = Area.objects.get(id=1)
# b Is a The object of the province of the city 
b = a.parent

If you know a province called a, you want to find out what city it has.


department = models.ForeignKey('Department', on_delete=models.CASCADE)
4

Related articles: