Model layer - common fields

Posted by blogfisher on Fri, 21 Jan 2022 02:15:29 +0100

Common fields and parameters

 

1 ORM field

AutoField

int auto increment column, the parameter primary must be filled in_ key=True. If there is no auto increment column in the model, a column named id will be automatically created.

IntegerField

An integer type ranging from - 2147483648 to 2147483647.

CharField

Character type, Max must be provided_ Length parameter, max_length indicates the character length.

DateField

Date field, date format: YYYY-MM-DD, equivalent to datetime in Python Date() instance.

DateTimeField

Date time field, format yyyy-mm-dd HH: mm [: SS [. Uuuuuuuuuuuu]] [TZ], equivalent to datetime in Python Datetime() instance

Common and non common fields

2 ORM field parameters

null

Used to indicate that a field can be empty.

unique

If set to unique=True, the field must be unique in this table.

db_index

If db_index=True means that the index is set for this field.

default

Set the default value for this field.

DateField and DateTimeField

auto_now_add

Configure auto_now_add=True, the current time will be added to the database when creating the data record.

auto_now

Configure auto on_ Now = true, this field will be updated every time the data record is updated.

 

3 Relation field

ForeignKey

Foreign key type in ORM Used to represent foreign key associations in ForeignKey Field set in 'One to many'in'many'The other side.

ForeignKey It can be associated with other tables and itself.

to

Sets the table to associate

to_field

Set the fields of the table to associate

related_name

The field name used in the reverse operation is used to replace the field name used in the original reverse query'Table name_set'.

For 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 will write this:

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

When we add the parameter "related" in the ForeignKey field_ Name , after,

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 will write this:

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

related_query_name

The join prefix used in the reverse query operation, which is used to replace the table name.

on_delete

When deleting data in an associated table, the behavior of the current table and its associated rows.

  models.CASCADE
Delete the associated data and delete the associated data


  models.DO_NOTHING
Deleting associated data raises an error integrity error


  models.PROTECT
Deleting associated data raises the error ProtectedError


  models.SET_NULL
Delete the associated data and set the associated value to null (provided that the FK field needs to be set to nullable)


  models.SET_DEFAULT
Delete the associated data and set the associated value as the default value (provided that the FK field needs to be set as the default value)


  models.SET

Delete associated data,
a. set the associated value to the specified value, setting: models Set (value)
b. the value associated with it is set as the return value of the executable object. Setting: models Set (executable object)

def func():
    return 10

class MyModel(models.Model):
    user = models.ForeignKey(
        to="User",
        to_field="id",
        on_delete=models.SET(func)
    )

db_constraint

Whether to create a foreign key constraint in the database. The default is True.

OneToOneField

One to one field.

Usually, one-to-one fields are used to extend existing fields.

The one-to-one association relationship is often used when the query frequency difference between different fields in a table is too large. The fields that could have been stored in one table are disassembled and placed in two tables, and then the two tables establish a one-to-one association relationship.

class Author(models.Model):
    name = models.CharField(max_length=32)
    info = models.OneToOneField(to='AuthorInfo')
    

class AuthorInfo(models.Model):
    phone = models.CharField(max_length=11)
    email = models.EmailField()

 

to

Set the table to associate.

to_field

Set the fields to associate.

on_delete

Same as ForeignKey field.

ManyToManyField

Used to represent many to many relationships. In the database, the association relationship is established through the third table

to

Sets the table to associate

related_name

Same as ForeignKey field.

related_query_name

Same as ForeignKey field.

symmetrical

It is only used to specify whether to create a reverse operation internally when many to many Auto Association. The default is True.

for instance:

class Person(models.Model):
    name = models.CharField(max_length=16)
    friends = models.ManyToManyField("self")

At this point, the person object has no person_set property.

class Person(models.Model):
    name = models.CharField(max_length=16)
    friends = models.ManyToManyField("self", symmetrical=False)

At this point, the person object can now use person_ Use the set property to reverse the query.

through

When using the ManyToManyField field, Django will automatically generate a table to manage many to many relationships.

However, we can also manually create the third table to manage the many to many relationship. At this time, we need to specify the table name of the third table through through.

through_fields

Set the associated field.

db_table

The name of the table in the database when the third table is created by default.

4 three ways of many to many Association

Method 1: create the 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's name")


# Create the third table by yourself and associate books and authors through foreign keys respectively
class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

    class Meta:
        unique_together = ("author", "book")

Method 2: automatically create the third table through ManyToManyField

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="title")


# Automatically create the third table through the ManyToManyField provided by ORM
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author's name")
    books = models.ManyToManyField(to="Book", related_name="authors")

Method 3: set ManyTomanyField and specify the third self created table

class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="title")


# Create the third table by yourself and specify the association through ManyToManyField
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="Author's name")
    books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))
    # through_fields accepts a 2-tuple ('field1 ',' field2 '):
    # Where field1 is the name of the foreign key of the model defining ManyToManyField (author), and field2 is the name of the foreign key of the associated target model (book).


class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

    class Meta:
        unique_together = ("author", "book")

 

be careful:

The third method is used when we need to store additional fields in the third relational table.

However, when we use the third method to create many to many relationships, we cannot use the methods of set, add, remove and clear to manage many to many relationships. We need to manage many to many relationships through the model of the third table.

5 yuan Information

The class corresponding to ORM contains another Meta class, which encapsulates some database information. The main fields are as follows:

db_table

The table name of ORM in the database is app by default_ Class name, which can be passed through db_table can override the table name.

index_together

Union index.

unique_together

Federated unique index.

ordering

Specifies what fields are sorted by default.

Only when this property is set can the query result be reversed ().

6 Custom fields (understand)

custom char Type field:

class FixedCharField(models.Field):
    """
    Custom char Field class of type
    """
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)

    def db_type(self, connection):
        """
        The field type of the restricted generated database table is char,Count Reg max_length Specified value
        """
        return 'char(%s)' % self.max_length


class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # Use custom char type fields
    cname = FixedCharField(max_length=25)
 
2
0