model

This is the fourth day of my participation in the August Text Challenge.More challenges in August

The model is the only, unambiguous source of information about your data. It contains the basic fields and behavior of the data you store. Typically, each model maps to a single database table.

Basic knowledge:

  • Each Model is a Python class that is derived from Django.db.models.Model.
  • Each property of the model represents a database field.

Example 1.

This example model defines a Person with a first_name and last_name:

from django.db import models
​
class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
Copy the code

First_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

The Person model above will create a database table like this:

CREATE TABLE app_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);
Copy the code

Description:

  • An App_person is generated in the database. This database name can be overridden by db_TABLE

    • db_table = 'test_person'
      Copy the code
  • We did not create the ID field, but we will add it by default, but this ID can be overridden

    • id = models.BigAutoField(primary_key=True)
      Copy the code

2. Use models

Once we have defined the model class, we need to migrate it to the database

Python Manage.py Makemigrations # Generate migration files, names and Hoisting # migrations. Python Manage.py Migrate # MigrationsCopy the code

Note:

If we hadn’t registered INSTALLED_APPS in settings.py, we wouldn’t have migrated it. Don’t forget to use it

INSTALLED_APPS = [... 'app', # self registered with startApp...]Copy the code

3. Field type

The following table lists all of Django’s built-in field types, but not the relational field types.

type instructions
AutoField An automatically incremented integer type field. Usually you dont need to write it yourself, Django will automatically add fields for you:id = models.AutoField(primary_key=True), this is an increment field, counting from 1. If you must set the primary key yourself, be sure to set the field toprimary_key=True. Django allows only one increment field in a model, and that field must be the primary key!
BigAutoField The 64-bit integer is an autoincrement field with a larger number range from 1 to 9223372036854775807
BigIntegerField A 64-bit IntegerField similar to IntegerField, from -9223372036854775808 to 9223372036854775807. In Django’s template form, this is shown as oneNumberInputThe label.
BinaryField A field that stores raw binary data.
BooleanField Boolean value type. The default value is None. This is represented in the HTML form as the CheckboxInput tag. If null=True is set, the NullBooleanSelect box is displayed. You can provide the default parameter value to set the default value.
CharField The most common type, the string type. You must accept a max_length argument, indicating that the string length cannot exceed this value. The default form tag is Text Input.
DateField auto_now: Automatically sets field to present (current time) when saving objectsauto_now_add: Automatically sets the field to present when the object is first created. Used to create a timestamp
DateTimeField Date and time, in Python bydatetime.datetimeInstance representation.
DecimalField A fixed precision decimal number, which in Python is composed of oneDecimalInstance representation. There are twoThe necessaryparameter
DurationField The field used to store the time period
EmailField useCharFieldTo check if the value is a valid E-mail address
FileField File upload field.
FilePathField The file path type is described separately later
FloatField Floating point type, corresponding to Python float. Refer to the integer type field.
ImageField Image types, described separately later.
IntegerField Integer type, one of the most commonly used fields. The value ranges from 2147483648 to 2147483647. This is represented in HTML as a NumberInput or TextInput tag.
GenericIPAddressField class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options),IPV4 or IPV6 address. The value is a string, for example192.0.2.30or2a02:42fe::4. This is represented in HTML as the TextInput tag. parameterprotocolThe default value is’ both ‘, which can be ‘IPv4’ or ‘IPv6’, indicating your IP address type.
JSONField JSON field. Django3.1 added. Signature forclass JSONField(encoder=None,decoder=None,**options). Encoder and decoder are optional encoder and decoder, used to customize the encoding and decoding mode. If you provide a default value for this field, make sure that the value is an immutable object, such as a string object.
PositiveBigIntegerField Positive large integers, 0 to 9223372036854775807
PositiveIntegerField Positive integers from 0 to 2,147,483,647
PositiveSmallIntegerField Smaller positive integers, from 0 to 32,767
SlugField Slug is a journalistic term. A slug is a short tag for something that contains letters, numbers, underscores, or links, usually in URLs. You can set the max_length parameter, which defaults to 50.
SmallAutoField Django3.0 added. Similar to AutoField, but only allowed from 1 to 32767.
SmallIntegerField A small integer ranging from -32768 to 32767.
TextField Used to store large amounts of text content, represented in HTML as Textarea tags, one of the most commonly used field types! If you set a max_length parameter to it, it will be limited by the number of characters in the front page, but not at the model and database level. Only CharField can work on both.
TimeField Time field, an instance of Datetime. time in Python. Accepts the same parameters as DateField, and applies only to hours, minutes, and seconds.
URLField A string type used to save the URL address. The default length is 200.
UUIDField A field used to hold Universally Unique identifiers. Use Python’s UUID class. It is saved as a UUID in the PostgreSQL database and as a char(32) in other databases. This field is the best alternative to an autoincrement primary key, as shown in an example below.

4. Relational fields

ForeignKey More than a pair of
OneToOneField One to one
ManyToManyField Many to many

5. Field options

null If True, null values can be stored. The default is False.
blank If True, the field is allowed to be null. Default False(True form validation will allow null values to be entered)
choices CHOICES = [(‘SR’, ‘Senior’), (‘GR’, ‘Graduate’),] The first element in each tuple is the actual value to be set on the model, and the second element is the readable name
db_column The name of the database column used for this field. If not, the name of the field is used.
db_index ifTrue, the database index is created for this field.
db_tablespace The name of the database tablespace (if the field is indexed) used for this field index. The default value is the ‘DEFAULT_INDEX_TABLESPACE setting for the project (if set) or the db_TABLESPACE model setting (if any). Ignore this option if the back end does not support index tablespaces.
default The default value for the field
editable If it isFalse, this field will not be in ModelForm. They are also skipped during model validation. The default isTrue.
error_messages theerror_messagesParameter allows you to override the default error message that this field will raise
help_text Additional Help text that is displayed with the form widget. Even if your field is not used on a form, it can be used in a document.
primary_key ifTrue, the field is the primary key of the model
unique ifTrue, the field must be unique in the entire table.
verbose_name The readable name of the field. If no detailed name is given, Django automatically creates the field using its property name, converting the underscore to a space

\