python's Django framework (ORM common fields and field parameters, relational fields and field parameters)

12.324 Django ORM Common Fields
1.id = models.AutoField(primary_key=True):int self-incrementing column, the parameter primary_key=True must be filled in.If there are no self-adding columns in the model, a column named ID is automatically created.
2.IntegerField: An integer type, ranging from -2147483648 to 2147483647
3.name = models.CharField(max_length=32):varchar character type, max_length parameter must be provided, max_length denotes character length
4.title = models.DateField(null=True): Date field, in the date format YYYY-MM-DD, equivalent to the datetime.date() instance in Python
5.title = models.DateTimeField(null=True): Date-time field in the format YYYY-MM-DD HH:MM[:ss[.uuuu]][TZ], equivalent to the datetime.datetime() instance in Python
6.TimeField(DateTimeCheckMixin, Field): - Time format HH:MM[:ss[.uuuuu]]
7.DurationField(Field): -Long integer, time interval, bigint storage in database, value obtained in ORM is of type datetime.timedelta
8. TextField: - Text type
9.FilePathField(Field): - String, Django Admin, and ModelForm provide the ability to read files under folders
        -Parameters:
                Path, folder path
                match=None, regular match
                recursive=False, recursive folder below
                allow_files=True, allow files
                allow_folders=False, allow folders
10.FileField: - String, path saved in database, file uploaded to specified directory
        -Parameters:
            upload_to =''save path to upload file
            storage = None storage component, default django.core.files.storage.FileSystemStorage
11.ImageField: - String, path saved in database, file uploaded to specified directory
        -Parameters:
            upload_to =''save path to upload file
            storage = None storage component, default django.core.files.storage.FileSystemStorage
            width_field=None, the highly saved database field name (string) of the uploaded picture
            height_field=None Upload Picture Width Saved Database Field Name (String)
12. FloatField: - Float
13.DecimalField: - Decimal decimal
                        - Parameters: max_digits, total length decimal_places, decimal length
14.BinaryField(Field): - Binary type

Custom Fields:

Custom char type field:

class FixedCharField(models.Field):
    def __init__(self, max_length, *args, **kwargs):
        super().__init__(max_length=max_length, *args, **kwargs)
        self.length = max_length
​
    def db_type(self, connection):
        """
        //Restrict the field type of the generated database table to char and the length to the value specified by length
        """
        return 'char(%s)' % self.length
​
class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # Use the custom above char Field of type
    cname = FixedCharField(max_length=25)

Customize unsigned int types:

class UnsignedIntegerField(models.IntegerField):
    def db_type(self, connection):
        return 'integer UNSIGNED'
    
class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # Use the unsigned custom above int Field of type
    cid = UnsignedIntegerField()
12.325 Field Parameters
title = models.DateField(null=True):Used to indicate that a field can be null
title = models.DateField(unique=True):If set to unique=True,Then the field must be unique in this table 
title = models.DateField(db_index=True):If db_index=True,Represents setting a database index for this field
price = models.DecimalField(max_digits=5, decimal_places=2, default=9.9):Set default values for this field
​
DatetimeField,DateField,TimeField:
publisher_date = models.DateField(auto_now_add): To configure auto_now_add=True,The current time is added to the database when a data record is created 
publisher_date = models.DateField(auto_now): Configuration auto_now=True,This field is updated each time a data record is updated   
12.326 Relational Field (ForeignKey)

Foreign key types are used in ORM to represent foreign key associations, typically setting the ForeignKey field on the'many'side of the'one-to-many'.ForeignKey can relate to other tables as well as to itself.

ForeignKey field parameters:

publisher = models.ForeignKey(to='Publisher', tofield='id' on_delete=models.CASCADE, db_constraint=False)
1.to: Set tables to be associated
2.to_field: Set the fields of the table to be associated with,
3.related_name: Field name used in reverse operation, instead of the original reverse query'Table Name_set'
4.related_query_name:Connection prefix used in reverse query operations to replace table names
5.on_delete=models.CASCADE:Behavior of the current table and its associated rows when data in the associated table is deleted,models.CASCADE Delete associated data and associate it with delete(1.1 Version default cascade deletion,2.0 Version must be added manually)
6.on_delete=models.SET()Delete the associated data,
a. The value associated with it is set to the specified value, setting: models.SET(value)  b. The value associated with it is set to the return value of the executable object, setting: models.SET(Executable Objects)
def func():
    return 10

class MyModel(models.Model):
    user = models.ForeignKey(
        to="User",
        to_field="id",
        on_delete=models.SET(func)
    )
7.db_constraint:Whether to set foreign key constraints in the database, default is True,Set to False,No constraints in the database, equivalent to a common field

Example:

class Classes(models.Model):
    name = models.CharField(max_length=32)
​
class Student(models.Model):
    name = models.CharField(max_length=32)
    theclass = models.ForeignKey(to="Classes")

When we want to query all the students associated with a class (reverse query), we would say this:

models.Classes.objects.first().student_set.all()

When we add the parameter related_name to the ForeignKey field:

class Student(models.Model):
    name = models.CharField(max_length=32)
    theclass = models.ForeignKey(to="Classes", related_name="students")

When we want to query all the students associated with a class (reverse query), we would say this:

models.Classes.objects.first().students.all()
12.327OneToOneField

One-to-one fields: Usually one-to-one fields are used to extend existing fields.

One-to-one associations are often used to split fields that could otherwise be stored in one table into two tables when the frequency gap between different field queries in one table is too large, and then establish one-to-one associations between the two tables.

class Author(models.Model):
    name = models.CharField(max_length=32)
    gender_choice = ((1, "male"), (2, "female"), (3, "secrecy"))
    gender = models.SmallIntegerField(choices=gender_choice, default=3)
    info = models.OneToOneField(to='AuthorInfo')
    
class AuthorInfo(models.Model):
    phone = models.CharField(max_length=11)
    email = models.EmailField(unique=True, db_index=True)
1.to:Set tables to be associated
2.to_field:Set the fields to be associated
3.on_delete:with ForeignKey field
12.328ManyToManyField

Used to represent many-to-many associations and to establish associations in a database through a third table

There are three ways to associate many-to-many relationships:

Mode 1: Create a third table by yourself

class Book(models.Model):
    title = models.CharField(max_length=32,verbose_name="Title")
​
class Author(models.Model):
    name = models.CharField(max_length=32,verbose_name="Author Name")
​
# Create a third table of your own
class Book2Author(models.Model):
    id = models.AutoField(primary_key=True)
    book = models.ForeignKey(to="Book")
    author = models.ForeignKey(to="Author")
    #first_blood = models.DateField() Create Chapter III tables on your own to facilitate adding new fields
    class Meta:
        unique_together = ("author", "book")
1.unique_together: Joint Unique Index
2.index_together: Joint Index
3.ordering: Specifies what field to sort by default.The result of the query can only be changed if this property is set reverse()

Mode 2: Automatically create the third table through ManyToManyField

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="Title")
    
# adopt ORM Incoming ManyToManyField Automatically create the third table
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author Name")
    books = models.ManyToManyField(to="Book", db_table="author2book",related_name="authors")  
    class Meta:
        db_table = "author"
1.to: Set tables to be associated
2.db_table="author2book":Specifies the name of the table for the third automatically created table author2book,Instead of app01_author_book
3.related_name="authors": Field name used in reverse operation, instead of the original reverse query'Table Name_set',with ForeignKey field
4.Meta:db_table,Establish author Specify table name when table author,Instead of app01_author

Mode 3: Set up ManyTomanyField and specify the third table you created yourself

class Book(models.Model):
    title = models.CharField(max_length=32,verbose_name="Title")
​
class Author(models.Model):
    name = models.CharField(max_length=32,verbose_name="Author Name")
    books = models.ManyToManyField(
        to="Book",
        through="Book2Author",
        through_fields=('author', 'book')
    )
    
# Create a third table of your own
class Book2Author(models.Model):
    id = models.AutoField(primary_key=True)
    book = models.ForeignKey(to="Book")
    author = models.ForeignKey(to="Author")
    #first_blood = models.DateField() Create Chapter III tables on your own to facilitate adding new fields
    class Meta:
        unique_together = ("author", "book")
1.to: Set tables to be associated      
2.through_fields:Set the associated field to accept a 2-tuple ('field1''field2'): among field1 Is Definition ManyToManyField The name of the model foreign key ( author),field2 Is the associated target model ( book)Foreign key name for the third table author,book Fields describe many-to-many relationships, and other fields ForeignKey Is a simple many-to-one foreign key.
3.through:in use ManyToManyField When field, Django A table is automatically generated to manage many-to-many relationships.But we can also manually create a third table to manage many-to-many relationships, which requires a through To specify the name of the third table.

Be careful:

But when we use the third way to create many-to-many relationships, we can't use set, add, remove, clear to manage many-to-many relationships. We can only use all to get objects. We need the model of the third table to manage many-to-many relationships.

12.3281 Query and other operations using Mode 1 or Mode 3

Query operation:

# Find the first book
ret = models.Book.objects.first().author2book_set.all().values("author__name")
ret = models.Book.objects.filter(id=1).values("author2book__author__name")

Add, delete and change actions:

first_book = models.Book.objects.first()
# Change: first_book.author.add(1):
models.Author2Book.objects.create(book=first_book, author_id=1)
# Empty: first_book.author.clear()
models.Author2Book.objects.filter(book=first_book).delete()
# Delete: first_book.author.remove(3)
models.Author2Book.objects.filter(book=first_book, author_id=3).delete()
# Check: first_book.author.all() Mode 3 is available
models.Author2Book.objects.filter(book=first_book)

Keywords: Python Database Django

Added by mubeena on Wed, 28 Aug 2019 04:53:30 +0300