1 definition

Define a model class in the models.py file as shown in the following example:

from django.db import models

# Create your models here.
Prepare the model class for the book list information
class BookInfo(models.Model) :
    # create field, field type...
    name = models.CharField(max_length=20, verbose_name='name')
    pub_date = models.DateField(verbose_name='Release Date',null=True)
    readcount = models.IntegerField(default=0, verbose_name='Reading volume')
    commentcount = models.IntegerField(default=0, verbose_name='Comment volume')
    is_delete = models.BooleanField(default=False, verbose_name='Logical delete')

    class Meta:
        db_table = 'bookinfo'  SQL > alter table name
        verbose_name = 'book'  # The name to display on the admin site

    def __str__(self) :
        Define the display information for each data object
        return self.name

Prepare the model class for the character list information
class PeopleInfo(models.Model) :
    GENDER_CHOICES = (
        (0.'male'),
        (1.'female')
    )
    name = models.CharField(max_length=20, verbose_name='name')
    gender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='gender')
    description = models.CharField(max_length=200, null=True, verbose_name='Description')
    book = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='book')  Outside the # key
    is_delete = models.BooleanField(default=False, verbose_name='Logical delete')

    class Meta:
        db_table = 'peopleinfo'
        verbose_name = 'People information'

    def __str__(self) :
        return self.name
Copy the code

1) Database table name

If the table name is not specified, Django defaults to lowercase app name _ Lowercase model class name database table name.

You can specify the database table name using db_table.

2) About primary keys

Django creates auto-growing primary key columns for tables. There is only one primary key column per model, and django does not create auto-growing primary key columns if you use the option to set a primary key column for a property.

The default primary key column attribute is ID. Pk can be used instead. Pk is the primary key.

3) Attribute naming restrictions

  • Cannot be a Python reserved key.
  • The use of consecutive underscores is disallowed because of the way Django queries are run.
  • When defining attributes, you need to specify the field type. The syntax is as follows:
Property = Models. Field type (option)Copy the code

4) Field type

type instructions
AutoField The auto-growing IntegerField is not usually specified. Django will automatically create an auto-growing IntegerField named ID if you do not specify it
BooleanField Boolean field with a value of True or False
NullBooleanField The value can be Null, True, or False
CharField The max_length parameter indicates the maximum number of characters
TextField Large text field, generally used when more than 4000 characters
IntegerField The integer
DecimalField A decimal floating point number with max_digits indicating the total number of digits and decimal_places indicating the decimal number
FloatField Floating point Numbers
DateField Date, the auto_now parameter means that this field is automatically set to the current time each time an object is saved. This is used for the “last modified” timestamp, which always uses the current date and defaults to False. The auto_now_add parameter indicates that the current time is automatically set when the object is first created. The timestamp used for creation is always the current date, which defaults to False; The auto_now_add and auto_now arguments are mutually exclusive, and combining them will cause an error
TimeField Time and parameters are the same as DateField
DateTimeField Date and time, parameters the same as DateField
FileField Upload file field
ImageField Inheriting from FileField, verifies uploaded content to ensure it is a valid image

5) options

options instructions
null If True, null is allowed. The default value is False
blank If True, the field is allowed to be blank, and the default is False
db_column The name of the field, if not specified, the name of the property is used
db_index If the value is True, the index for this field is created in the table, and the default is False
default The default
primary_key If True, this field becomes the primary key field of the model. The default value is False and is typically used as an AutoField option
unique If True, this field must have a unique value in the table, and the default value is False

Null is the database category concept, blank is the form validation category

6) foreign keys

When setting a foreign key, use the on_delete option to specify what to do with the foreign key reference table data when the primary table deletes data. Django.db. models contains optional constants:

  • CASCADE Indicates that data in the primary table can be deleted
  • PROTECT prevents the deletion of data applied by foreign keys from the primary table by raising ProtectedError
  • SET_NULL is set to NULL, available only if the field NULL =True allows NULL
  • SET_DEFAULT is set to the default value and is available only if the field has a default value
  • SET() sets a particular value or calls a particular method
  • DO_NOTHING does nothing, and this option raises an IntegrityError if cascade is specified in front of the database

2 the migration

Synchronize the model classes to the database.

1) Generate migration files

Python Manage.py MakemigRations 2) Synchronized to the database

python manage.py migrate