Django --- common fields and parameters

1 ORM field

Auto Field

int auto increment, must fill in the parameters primary_key = True. When the model, if there is no auto-increment, then automatically creates a column called id columns.

IntegerField

An integral type, in the range -2147483648 to 2147483647.

CharField

Character type, must provide max_length parameters, characters indicating max_length.

DateField

Date field, the date format YYYY-MM-DD, corresponding to the Python datetime.date () instance.

DateTimeField

Time field, the format YYYY-MM-DD HH: MM [: ss [.uuuuuu]] [TZ], corresponding to the Python A datetime.datetime () Example

And very commonly used by field

2 ORM field parameters

null

Is used to represent a field can be empty.

unique

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

db_index

If db_index = True represents the index field is set for this purpose.

default

Set the default value for the field.

DateField和DateTimeField

auto_now_add

Configuring auto_now_add = True, create a data record when the current time will be added to the database.

auto_now

Configuration auto_now = True, each time when updating the data record will update the field.

3 relationship field

ForeignKey

Foreign key is used to indicate the type of the foreign key relationship in the ORM, generally one of the fields provided ForeignKey 'many' in 'multiple' of.

ForeignKey can make tables and other relationships at the same time and can also make their own relationships.

to

Set the table to be associated

to_field

To set the table associated fields

When the reverse operation, field names used for table name _set 'instead of the original when the reverse lookup.

E.g:

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 a class association of all students (reverse lookup), we can write:

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

When we add in the parameters related_name 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 a class association of all students (reverse lookup), we can write:

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

Reverse query operation, connected prefix that replaces the table name.

on_delete

  When you delete data associated table, the current table row behavior associated with it.

  models.CASCADE
  delete the associated data associated with it also deleted

  models.DO_NOTHING
  delete the associated data, causing errors IntegrityError

  models.PROTECT
  association delete data, causing errors ProtectedError

  models.SET_NULL
  delete the associated data, the value associated therewith is null (the precondition FK field should be set to be empty)

  models.SET_DEFAULT
  delete the associated data, associated with the value set to the default value (FK premise fields need to set the default value)

  models.SET

  Delete the associated data,
  . A set value associated with the specified value, provided: models.SET (value)
  . B value associated executable object set as return value is provided: 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 field.

Usually one field to extend the existing field.

One association in the multi-purpose field when the query frequency gap a different table is too large, this will be stored in the open field in a table placed in the two tables, two tables and then establish one association.

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 be associated.

to_field

Set the field to be associated.

on_delete

With ForeignKey field.

ManyToManyField

Used to represent the relationship many to many. In the database to establish relationships through the third table

to

Set the table to be associated

With ForeignKey field.

With ForeignKey field.

symmetrical

When used only for self-many association, specify whether to create a field inside the reverse operation. The default is True.

for example:

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

In this case, person object is not person_set property.

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

In this case, person objects can now use a reverse lookup person_set attributes.

through

In use ManyToManyField field, Django will automatically generate a table to manage many to many relationship.

But we can also manually create a third table to manage many relationships, then you need to specify the table name by a third table through.

through_fields

Set field associated with it.

db_table

When the third table is created by default, the name of the database table.

4-many relationships in three ways

One way: create your own third table

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


class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")


# 自己创建第三张表,分别通过外键关联书和作者
class Author2Book(models.Model):
    author = models.ForeignKey(to="Author")
    book = models.ForeignKey(to="Book")

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

Copy the code

Second way: automatically create a third table by ManyToManyField

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


# 通过ORM自带的ManyToManyField自动创建第三张表
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")
    books = models.ManyToManyField(to="Book", related_name="authors")
class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="书名")


# 自己创建第三张表,并通过ManyToManyField指定关联
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name="作者姓名")
    books = models.ManyToManyField(to="Book", through="Author2Book", through_fields=("author", "book"))
    # through_fields接受一个2元组('field1','field2'):
    # 其中field1是定义ManyToManyField的模型外键的名(author),field2是关联目标模型(book)的外键名。


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

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

note:

When we need to store additional fields in the third relational tables, it is necessary to use a third way.

But when we create a third way to use-many relationship, you can not use the set, add, remove, clear way to manage many relationships, and the need to manage many relationships through third model table .

5 yuan Information

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

db_table

ORM table name in the database by default app_ class name, you can db_table can override the table name.

index_together

Joint index.

unique_together

United unique index.

ordering

What specify the default sort field.

Only set this property, we query the results can be reverse ().

6 custom fields (understanding)

Custom char type field:

class FixedCharField(models.Field):
    """
    自定义的char类型的字段类
    """
    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):
        """
        限定生成数据库表的字段类型为char,长度为max_length指定的值
        """
        return 'char(%s)' % self.max_length


class Class(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=25)
    # 使用自定义的char类型的字段
    cname = FixedCharField(max_length=25)

Refer to blog: https://www.cnblogs.com/Dominic-Ji/p/9203990.html

Guess you like

Origin www.cnblogs.com/whkzm/p/11953600.html