Django learning record 14

Relational mapping

The relational mapping in the database can be one-to-one, one to many and many to many.

1, One on one

When two tables have a one-to-one relationship, define a foreign key inside any model class.

Create a one-to-one mapping:

class A(models.Model):
	pass
class B(models.Model):
	a=models.OneToOneField(A,on_delete=***)

After creation, the foreign key field name will change to name
name_id

on_delete cascade delete action specifies.
Optional:
①models.CASCADE deletion of cascade (concatenation, life and death together. After deleting one, the other will also be deleted). django does not set cascade deletion at the mysql level and uses ORM for management.
②models.PROTECT throws a ProtectedError exception to prevent the deletion of the referenced object. (same as mysql by default. Deletion is not allowed when there is a link relationship)
③SET_NULL set ForeignKey null; Deletion is allowed, and the foreign key originally pointing to it points to NULL (to set this cascade deletion method, the foreign key field must be set to null=True, that is, the field must be nullable)
④SET_DEFAULT sets ForeignKey as its default value (to set this cascading deletion method, the foreign key field must be set as the default value)

Create data:
For model classes without foreign keys (pointed classes)
Create directly using create

a=mymodela.objects.create(a0='***')

For model classes with foreign keys
Associated fields should also be given when creating
eg: if b0 is associated with a0, you can use
Class name = class object name
One to one correspondence

b=mymodelb.objects.create(b0='***',a0=a)

Or directly use the field of the foreign key to correspond,
Corresponding foreign key field = field content

b=mymodelb.objects.create(b0='***',a0_id='***')

eg: create husband and wife classes, one-to-one correspondence.
① Create a new app WiFi (remember to register)
② Create two new model classes, man and woman
The man field in woman corresponds to the man model class

from django.db import models

# Create your models here.
class man(models.Model):
    manname=models.CharField(max_length=50,default='')
class woman(models.Model):
    womanname=models.CharField(max_length=50,default='')
    man=models.OneToOneField(man,on_delete=models.CASCADE)



③ After creating a new man object, use class name = class object name to create woman
Import class.

New man object man1

Create a woman object corresponding to man1

④ After creating a new man object, use class field = class field to create woman

The final object created is

Query data:

1. Forward query

In the above example, query man by woman (query the associated object by foreign key)
You can get the corresponding class object through direct dot access
eg:

woman1=woman.objects.get(womanname='Li Si's wife')
print(woman1.womanname,'My husband is',woman1.man.manname)

2. Reverse query

The reverse attribute can be used to query the associated content.
django defines a hidden attribute with the same name (lowercase) as the associated class in the associated class, which can also be accessed directly by dot
However, if the field is not associated, an error will be reported.

man1=man.objects.get(manname='Li Si')
print(man1.manname,'My wife is',man1.woman.womanname)

2, One to many

One to many creates a foreign key in a "many" table.

class A(models.Model):
	pass
class B(models.Model):
	a=models.ForeignKey(A,on_delete=***)

There are still two ways to create fields in the same one-to-one way.

The query method is one-to-one, and it is still dot access to obtain objects. Reverse query is different
Use examples to illustrate:
eg:

class A(models.Model):
	pass
class B(models.Model):
	a=models.ForeignKey(A,on_delete=***)

Viewing B through A is A reverse query. Since one A can correspond to many B's, it cannot be accessed directly.
To pass:

#First, get the class A object dataA
dataA=A.objects.get(***)
#1. Pass B_set is equivalent to objects of class B, which can be followed by all methods, all, filter,get You can even use create to create a B object
Bs=dataA.B_set.all()
#2. Obtained by field filtering
Bs=B.objects.filter(a=dataA)

3, Many to many

mysql is implemented by relying on the third table.
django does not need to create the third table manually, but still uses similar special attributes.
Syntax:
Add in any of the two associated classes

class A(models.Model):
	pass
class B(models.Model):
	a=models.ManyToManyField(A)

In fact, the essence of this operation is that django automatically creates the third table, but it does not need to be related in the operation. You can directly use django's internal attributes to operate it.
Create and query the same one to many reverse query.
eg:

class Author(models.Model):
	authorname=models.CharField(max_length=50,default='')
class Book(models.Model):
	bookname=models.CharField(max_length=50,default='')
	author=models.ManyToMany(Author)

It doesn't matter which one is created first. You can create and associate freely.
eg: create a book "101 moves to prison", compiled by Zhang San and Li Si.

author1=Author.objects.create(authorname='Zhang San')
author2=Author.objects.create(authorname='Li Si')
book1=author1.book_set.create(bookname='101 moves to prison')
author2.book_set.add(book1)

book1=author1.book_set.create(bookname='101 moves to prison')
author1=Author.Book.create(authorname='Zhang San')
author2=book.Author.create(authorname='Li Si')
book1.Author.add(author2)

Query:
One to many method in one to many, but the forward direction is mybook Author. all()
Reverse to myauthor Book_ set. all()

Summary!!!
When the class of the foreign key operates on its associated class, you can directly use:
The object name of the class where the foreign key is located Corresponding class object name create/all/filter…()
When operating in reverse, use:
Corresponding class object name Class object name of foreign key_ set.create/all/filter…()
When both objects exist, to bind, use the method of add (object).

Keywords: Python MySQL Django

Added by outpost on Mon, 31 Jan 2022 14:44:19 +0200