SoFunction
Updated on 2024-11-20

Python Django Models Explained

Django Models

Django's models are defined in files. A model is the M in MVT, which is also equivalent to the M in MVC.

In Django, models must inherit from the Model class. For example:

from  import models
# Create your models here.
class BookInfo():       # A model class generates a table in the database.
    """Book Modeling"""  
    name = (max_length=128, verbose_name='Name')        # The properties of a class are the fields in a data table.
    pub_date = (verbose_name='Date of release',null=True)
    readcount = (default=0, verbose_name='Readership')
    commentcount = (default=0, verbose_name='Number of comments')
    is_delete = (default=False, verbose_name='Logical deletion')
    class Meta:     # class Meta is a fixed writeup
        db_table = 'bookinfo'      # Specify the database table name
        verbose_name = 'Books'       # Name displayed in the admin site

take note of

1. If the model class does not specify the table name, Django defaults to lowercase app application name_lowercase model class name database table name, generally we will specify the database table name through db_table.

will create auto-growing primary key columns for the table, each model can only have a primary key column, if you use the option to set an attribute as the primary key column after django will not create auto-growing primary key columns. By default, the primary key column is created with the attribute id, or you can use pk, which means primary key.

3. Double underscores cannot appear in the field name because it is one of Django's query syntax.

Since Django 3.2, you can configure the DEFAULT_AUTO_FIELD parameter to set the data type of the primary key, the default is DEFAULT_AUTO_FIELD = ''Before Django 3.2, the default primary key data type generated was AutoField.

Here are the details of the commonly used field types in Django

Field type

typology clarification
BigAutoField Auto-growth BigIntegerField, usually do not need to specify, do not specify when Django will automatically create a property named id auto-growth properties
BooleanField Boolean field with a value of True or False
NullBooleanField Supports Null, True and False values.
CharField String, max_length is the maximum number of characters.
TextField Large text field, generally used when over 4000 characters
IntegerField integer (math.)
DecimalField Decimal floating point number, the parameter max_digits indicates the total number of digits, the parameter decimal_places indicates the number of decimal places.
FloatField floating point
DateField date, the parameter auto_now means automatically set this field to the current time every time the object is saved, which is used for the "last modified" timestamp, it always uses the current date, the default is False; the parameter auto_now_add means automatically set the current time when the object is created for the first time, which is used for the creation timestamp, it always uses the current date, the default is False; the parameters auto_now_add and auto_now are mutually exclusive, the combination will result in an error. False; the parameters auto_now_add and auto_now are mutually exclusive, and the combination will result in an error
TimeField Time, same parameters as DateField
DateTimeField Date and time, same parameters as DateField
FileField Upload File Fields
ImageField Inherits from FileField and checks the uploaded content to make sure it's a valid image

Here are the parameters in the field type

Parameters for field types

parameters clarification
null If True, null is allowed, the default value is False.
blank If True, the field is allowed to be blank, the default value is False
db_column The name of the field, or the name of the attribute if not specified
db_index If True, then an index will be created for this field in the table, the default value is False.
default Assigning Default Values to Fields
primary_key If True, the field will become the primary key field of the model, the default value is False, generally used as an option for AutoField
unique If True, this field must have a unique value in the table, the default value is False.
choices This parameter provides options from a series of binary groups

take note of

The field must be specified with the parameter max_length

2. You can also specify the parameter verbose_name for the field. This parameter is mainly used in the admin management page and is actually related to localization. For example, you can specify the parameter verbose_name="book name" in the name field above, then you will see the book name in the admin page.

parameter is the database level, after setting null=True, it means that the field of the database can be empty; blank parameter is the form level (HTML), after blank=True, it means that the form can be filled in when the field is not filled in.

foreign key

Foreign keys are something that are usually implemented at the business logic level, not in the database. But usually in the database courses you take, there are database design paradigms, and one of them, the third paradigm, is dedicated to foreign key constraints. Here is just a brief introduction. Here's another model that is related to the BookInfo model from earlier by a foreign key.

class PeopleInfo():
    """Staffing model"""
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    name = (max_length=20, verbose_name='Name')
    gender = (choices=GENDER_CHOICES, default=0, verbose_name='Gender')
    description = (max_length=200, null=True, verbose_name='Description information')
    book = (BookInfo, on_delete=, verbose_name='Books')  # Foreign keys
    is_delete = (default=False, verbose_name='Logical deletion')
    class Meta:
        db_table = 'peopleinfo'
        verbose_name = 'Character Information'
Here are the highlightschoicesThis parameter is the same as the。
choicesThe parameter is the binary from our definition(GENDER_CHOICES)Get value in。The first value of the binary is stored in the database,and the second value will only be used to display in the form the。For a model instance,To get the second corresponding value in the binary of the field,utilization get_FOO_display() methodologies。for example:Get the gender information above,可以utilizationget_gender_display()methodologies。
foreign key:通过utilization来设置foreign key,ForeignKeyThe first parameter is the name of the model class to be associated with.,The second parameter ison_delete。Its common values can be as follows:
CASCADEcascade,删除主表数据时连通一起删除foreign key表中数据
PROTECTsafeguard,By throwing theProtectedErrorexceptions,来阻止删除主表中被foreign key应用的数据
SET_NULLset toNULL,Only in this fieldnull=Trueallowed tonullcurrently available
SET_DEFAULTset to默认值,Only in this field设置了默认值currently available
SET()set to特定值或者调用特定methodologies
DO_NOTHINGNo operation,如果数据库前置指明cascade性,This option throws theIntegrityErrorexceptions

Note: When we set up a foreign key in a database, we need to specify the associated field in another table, but it is not specified in Django. This is because Django will specify the id of another table as the associated field by default. As shown in the figure below:

在这里插入图片描述

You can see that the foreign key name in the peopleinfo table is book_id

summarize

That's all for this post, I hope it helped you and I hope you'll check back for more from me!