Defining model classes

  • The model classes are defined in the “Application/Models.py” file, in this case the “booktest/models.py” file
  • The Model classes must inherit from the Model class and reside in the package django.db.models
  • Tip: Use logical deletions for important data

Custom properties

  • Django determines the following information based on the type of attribute:
  1. The type of field supported by the currently selected database
  2. The default HTML control to use when rendering administrative forms
  3. Minimum validation at admin site
  • 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
  • Attribute naming restrictions
  1. Cannot be a Python reserved key
  2. 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
  • The following sections explain what field types and options are available

The field type

  • To use it, you need to import the django.db.models package with the following field types
  • AutoField: An auto-growing IntegerField. If you do not specify this, Django automatically creates an auto-growing attribute named ID
  • BooleanField: BooleanField with a value of True or False
  • NullBooleanField: Supports Null, True, and False values
  • CharField(max_length= character length) : a character string
    • The Max — lenght parameter indicates the maximum number of characters
  • TextField: large TextField, usually used when more than 4000 characters are in length
  • IntegerField: integer
  • DecimalField(max_digits=None, decimal_places=None) : Decimal floating point number
    • The max_dight argument represents the total number of digits
    • The parameter Decimal_places represents the number of decimal places
  • FloatField: indicates the floating point number
  • DateField[auto_now=False, auto_now_add=False]) : date
    • The auto_now parameter means that each time an object is saved, this field is automatically set to the current time 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, same parameter as DateField
  • DateTimeField: date and time. The parameters are the same as DateField
  • FileField: indicates the upload FileField
  • ImageField: Inherits from FileField and verifies uploaded content to ensure it is a valid image

options

  • Constraints on fields are implemented with the following options:
  • Null: If True, null is allowed. The default value is False
  • Blank: This field is allowed to be blank if True. The default is False
  • Contrast: NULL is a database category, blank is a form validation category
  • Db_column: Specifies the name of the field. If not specified, the name of the property is used
  • Db_index: If True, an index is created for this field in the table. The default value is False
  • Default: indicates the default value
  • Primary_key: If True, this field becomes the primary key field of the model. The default value is False and is usually used as an AutoField option
  • Unique: If True, this field must have a unique value in the table. The default value is False

Relational field type

  • There are three types of relational databases:
    • ForeignKey: One-to-many, which defines fields on the many end
    • ManyToManFeld: Many-to-many, with fields defined at both ends
    • OneToOneField: One on one. Define fields on either end
  • Recursive associations can be maintained, specified using “selt”, as described in ‘self association’
  • One to many access syntax:
Model class Lowercase _set Example: bookinfo.heroinfo_setCopy the code
  • Access syntax from one to one
Model class lowercase example: Heroinfo.bookinfoCopy the code
  • Access the ID syntax of the associated object
Property _id Example: Heroinfo.book_idCopy the code

Yuan options

  • The default name of the data table is
"App_name > _ < model_name > example: booktest_bookinfoCopy the code
  • Define class Meta in the model class to set Meta information, such as the name of a custom table using DB_TABLE

Example demonstrates

  • Next, take book-hero management as an example to demonstrate. Today, we mainly explain the operation part of the model

Open the booktest/models.py file and define the model class as follows

From django.db import models # define bookInfo class bookInfo (models.model): Btitle = models.charfield (max_length=20) # book name bpub_date = models.datefield () # publish date braed = Models.IntegerField(default=0) # bcommet = models.IntegerField(default=0) # Models.BooleanField(default=False) # Db_table = 'bookinfo' # Create your models here. Hname = models.charfield (max_length=20) # Hero name hgender = Models.booleanfield (default=True) # hero gender isDelete = Models.booleanfield (default=False) # HContent = Models.charfield (max_length=100) # hero description hbook = Models.foreignKey ('BookInfo') # The relationship between the hero and the book table is one-to-many, so the attributes are defined in the hero modelCopy the code

The migration

  • Generate migration
python manage.py makemigrations
Copy the code
  • Perform the migration
python manage.py migrate
Copy the code

  • Open the database command to view all the current tables as shown in the following figure

  • The bookinfo table is structured as follows
  • Default values do not apply at the database level, but when Django creates objects

  • The booktest_Heroinfo table has the following structure
  • Generate a relationship field based on the relationship property and create a foreign key constraint

The test data

  • On the database command line, copy the following statement
Insert into bookinfo (btitle, bpub_date braed, bcommet, isDelete) values (' the legend of the condor heroes', '1980-5-1', '12. , '34', '0'), (" tian long ba bu ", '1986-7-24', '36', '40', '0'), (' thrive ', '1995-12-24', '20', '80', '0'), (' Snow Mountain Flying Fox ','1987-11-11','58','24','0');Copy the code

  • Copy the following statement and execute it