Define model classes
- Model classes are defined in the "application / models.py" file.
- The Model class must inherit from the Model class, located in the package Django db. In models
1 . definition
Create the application booktest in models Py file.
from django.db import models #Define book model class BookInfo class BookInfo(models.Model): btitle = models.CharField(max_length=20, verbose_name='name') bpub_date = models.DateField(verbose_name='Release date') bread = models.IntegerField(default=0, verbose_name='Reading volume') bcomment = models.IntegerField(default=0, verbose_name='Comment volume') is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') class Meta: db_table = 'tb_books' # Indicates the database table name verbose_name = 'books' # The name displayed in the admin site verbose_name_plural = verbose_name # Plural names displayed def __str__(self): """Define the display information for each data object""" return self.btitle #Define hero model class HeroInfo class HeroInfo(models.Model): GENDER_CHOICES = ( (0, 'female'), (1, 'male') ) hname = models.CharField(max_length=20, verbose_name='name') hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='Gender') hcomment = models.CharField(max_length=200, null=True, verbose_name='Description information') hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='books') # Foreign key is_delete = models.BooleanField(default=False, verbose_name='Logical deletion') class Meta: db_table = 'tb_heros' verbose_name = 'hero' verbose_name_plural = verbose_name def __str__(self): return self.hname
1) Database table name
If the model class does not specify the table name, Django uses lowercase app application name by default_ The lowercase model class name is the database table name.
Available through db_table indicates the database table name.
2) About primary keys
django will create an automatically growing primary key column for the table. Each model can only have one primary key column. If you use the option to set a property as a primary key column, django will not create an automatically growing primary key column.
By default, the created primary key column attribute is id, which can be replaced by pk. pk is fully spelled as primary key.
3) Attribute naming restrictions
- Cannot be a reserved keyword for python.
- Continuous underscores are not allowed, which is determined by django's query method.
- When defining attributes, you need to specify the field type. You can specify options through the parameters of the field type. The syntax is as follows:
4) Field type
type explain AutoField Automatic growth IntegerField,It is usually not specified. When it is not specified Django The property named id Auto growth properties of BooleanField Boolean field with a value of True or False NullBooleanField support Null,True,False Three values CharField String, parameter max_length Indicates the maximum number of characters TextField Large text field, generally used when it exceeds 4000 characters IntegerField integer DecimalField Decimal floating point number, parameter max_digits Indicates the total number of digits, parameter decimal_places Represents the number of decimal places FloatField Floating point number DateField Date, parameter auto_now Indicates that this field is automatically set as the current time each time an object is saved, which is used to"Last modification"It always uses the current date. The default is False; parameter auto_now_add Indicates that the current time is automatically set when the object is created for the first time. It is used to create the timestamp. It always uses the current date. The default is False; parameter auto_now_add and auto_now If they are mutually exclusive, the combination will be wrong TimeField Time, same as parameters DateField DateTimeField Date and time, the same as parameters DateField FileField Upload file field ImageField Inherit from FileField,Verify the uploaded content to ensure that it is a valid picture
5) Options
option explain null If yes True,Indicates that it is allowed to be empty. The default value is False blank If yes True,The field is allowed to be blank, and the default value is False db_column The name of the field or, if not specified, the name of the property db_index If the value is True, An index will be created for this field in the table. The default value is False default default primary_key if it is True,This field will become the primary key field of the model. The default value is False,General Act AutoField Use of options unique If yes True, This field must have a unique value in the table. The default value is False
null is the concept of database category, and blank is the concept of form verification category
6) Foreign key
When setting foreign keys, you need to pass on_ The delete option indicates how to handle the foreign key reference table data when deleting data from the main table. See Django db. Models contains optional constants:
- CASCADE cascade. When deleting the data in the main table, the data in the foreign key table is deleted together
- PROTECT, by throwing a ProtectedError exception, prevents the deletion of data applied by foreign keys in the main table
- SET_NULL is set to null and is available only if the field null=True allows nulls
- SET_DEFAULT is set to the default value and is available only if the field has a default value set
- SET() to a specific value or call a specific method, such as
from django.conf import settings from django.contrib.auth import get_user_model from django.db import models def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), )
- DO_ Noting does not do anything. If the database prefix indicates cascading, this option will throw an integrity error exception
2 migration
Synchronize model classes to the database.
1) Generate migration file
python manage.py makemigrations
- Synchronize to database
python manage.py migrate
3 add test data
insert into tb_books(btitle,bpub_date,bread,bcomment,is_delete) values ('Legend of Shooting Heroes','1980-5-1',12,34,0), ('Tianlong Babu','1986-7-24',36,40,0), ('Xiaoao Jianghu','1995-12-24',20,80,0), ('Snow mountain flying fox','1987-11-11',58,24,0);
insert into tb_heros(hname,hgender,hbook_id,hcomment,is_delete) values ('Guo Jing',1,1,'Eighteen dragon subduing palms',0), ('Huang Rong',0,1,'Dog beating stick',0), ('pharmacist hwang',1,1,'Finger flicking magic power',0), ('Ouyang Feng',1,1,'Toad skill',0), ('Mei Chaofeng',0,1,'Jiuyin White Bone Claw',0), ('Qiao Feng',1,2,'Eighteen dragon subduing palms',0), ('duan yu',1,2,'six miles holy sword',0), ('Phyllostachys pubescens',1,2,'Tianshan Liuyang palm',0), ('Wang Yuyan',0,2,'Fairy sister',0), ('linghu chong',1,3,'Dugu Jiujian',0), ('Ren yingying',0,3,'play the piano',0), ('yue buqun',1,3,'Huashan sword technique',0), ('invincible eastern',0,3,'Sunflower collection',0), ('Hu Fei',1,4,'mr Hu's',0), ('Miao Ruolan',0,4,'Yellow clothes',0), ('Cheng lingsu',0,4,'Medical skill',0), ('Yuan Ziyi',0,4,'Liuhequan',0);