In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
When creating tables through Django's ORM, we need to define our own classes. When defining a class, he has a variety of field types, each of which has its own parameters to configure, which are briefly summarized below.
First look at the type of field. Although Python offers nearly 20 types, when it is converted to a database table, it is essentially four types: string, number, time, and binary.
AutoField (Field)-int auto-increment column, you must enter the parameter primary_key=TrueBigAutoField (AutoField)-bigint auto-increment column, and you must enter the parameter primary_key=True note: if there is no self-increment column in model Then automatically create a column named id from django.db import models class UserInfo (models.Model): # automatically create an integer column named id username = models.CharField (max_length=32) class Group (models.Model): # Custom add column nid = models.AutoField (primary_key=True) name = models.CharField (max_length=32) SmallIntegerField (IntegerField):-small integer-32768 ~ 32767PositiveSmallIntegerField (PositiveIntegerRelDbTypeMixin IntegerField)-positive small integer 0 ~ 32767IntegerField (Field)-column of integers (signed)-2147483648 ~ 2147483647PositiveIntegerField (PositiveIntegerRelDbTypeMixin, IntegerField)-positive integer 0 ~ 2147483647BigIntegerField (IntegerField):-long integer (signed)-9223372036854775808 ~ 9223372036854775807 Custom unsigned integer field class UnsignedIntegerField (models.IntegerField): def db_type (self) Connection): return 'integer UNSIGNED' PS: the returned value is the property of the field in the database The default values for the Django field are: 'AutoField':' integer AUTO_INCREMENT', 'BigAutoField':' bigint AUTO_INCREMENT', 'BinaryField':' longblob', 'BooleanField':' bool', 'CharField':' varchar (% (max_length) s)', 'CommaSeparatedIntegerField':' varchar (% (max_length) s)', 'DateField':' date' 'DateTimeField': 'datetime',' DecimalField': 'numeric (% (max_digits) s,% (decimal_places) s)', 'DurationField':' bigint', 'FileField':' varchar (% (max_length) s)', 'FilePathField':' varchar (% (max_length) s)', 'FloatField':' double precision', 'IntegerField':' integer' 'BigIntegerField': 'bigint',' IPAddressField': 'char (15)', 'GenericIPAddressField':' char (39)', 'NullBooleanField':' bool', 'OneToOneField':' integer', 'PositiveIntegerField':' integer UNSIGNED', 'PositiveSmallIntegerField':' smallint UNSIGNED', 'SlugField':' varchar (% (max_length) s)' 'SmallIntegerField':' smallint', 'TextField':' longtext', 'TimeField':' time', 'UUIDField':' char (32)', BooleanField (Field)-Boolean type NullBooleanField (Field):-Boolean CharField (Field) that can be null-character type-max_length parameter must be provided Max_length represents character length TextField (Field)-text type EmailField (CharField):-string type, authentication mechanism IPAddressField (Field)-string type provided in Django Admin and ModelForm, authentication IPV4 mechanism GenericIPAddressField (Field)-string type in Django Admin and ModelForm, authentication Ipv4 and Ipv6-parameter: protocol in Django Admin and ModelForm, used to specify Ipv4 or Ipv6 'both', "ipv4", "ipv6" unpack_ipv4, if specified as True, can be resolved to 192.0.2.1 when entering:: ffff:192.0.2.1. Thorn function is enabled. Protocol= "both" URLField (CharField)-string type is required. Verification URLSlugField (CharField)-string type is provided in Django Admin and ModelForm. Validations provided in Django Admin and ModelForm support letter, number, underscore, hyphen (minus) CommaSeparatedIntegerField (CharField)-string type, format must be comma-separated numeric UUIDField (Field)-string type, Django Admin and ModelForm provide validation FilePathField (Field)-string for UUID format Django Admin and ModelForm provide the function to read files under a folder-parameters: path, folder path match=None, regular matching recursive=False, recursive folder allow_files=True, allow files allow_folders=False Allow folder FileField (Field)-string The path is saved in the database, and the file is uploaded to the specified directory-Parameter: upload_to = "" the save path of the uploaded file storage = None storage component, default django.core.files.storage.FileSystemStorageImageField (FileField)-string, and the path is saved in the database Upload the file to the specified directory-Parameter: upload_to = "" Save path of the uploaded file storage = None storage component Default django.core.files.storage.FileSystemStorage width_field=None, highly saved database field name (string) height_field=None uploaded picture width saved database field name (string)-date + time format YYYY-MM-DD HH:MM [: ss [.uuuuuuuu]] [TZ] DateField (DateTimeCheckMixin, Field)-date format YYYY-MM-DDTimeField (DateTimeCheckMixin) Field)-time format HH:MM [: ss [.uuuuuu]] DurationField (Field)-long integer Time interval, stored in the database according to bigint. The values obtained in ORM are datetime.timedelta type FloatField (Field)-floating point DecimalField (Field)-decimal-parameter: max_digits, total decimal length decimal_places, decimal length BinaryField (Field)-binary type.
For example, in the following example, CharField is a string, and EmailField is also a string. If you open it in the database, you can see that the type is varchar. So what's the difference between him? This is when managing the database through the Django admin page, he will automatically do a validation.
Example 1
Class UserInfo (models.Model): username = models.CharField (max_length=32,blank=True,verbose_name=' username') password = models.CharField (max_length=60, help_text='pwd') email = models.CharField (max_length=60) test = models.EmailField (max_length=19,null=True,error_messages= {'invalid':' Please enter password'}) user_group = models.ForeignKey ("UserGroup", to_field='uid') # (uid,catption,ctime Uptimew) user_type_choices = ((1, 'superuser'), (2, 'ordinary user'), (3, 'ordinary user'),) user_type_id = models.IntegerField (choices=user_type_choices,default=1)
Table structure of database
Django management interface. The first time you use it, you need to create a superuser, as shown in python manage.py createsuperuser. Then execute the registration in admin.py
For example
From django.contrib import adminfrom app01.models import userinfoadmin.site.register (userinfo)
After logging in, you can modify the contents of the table, and he will automatically verify the format.
Django admin interface
Example 2: the time type field is defined here, and I don't want to use the automatically generated id field, so I need to define a self-increasing primary key manually.
Class UserGroup (models.Model): uid = models.AutoField (primary_key=True) caption = models.CharField (max_length=32,unique=True) ctime = models.DateTimeField (auto_now_add=True, null=True) uptime = models.DateTimeField (auto_now=True, null=True)
We need to emphasize the time type here. If USE_TZ=True is set in setting, the time saved in the database is always the time of UTC. If you need to display other times in the template, you can modify TIME_ZONE='Asia/Shanghai', so that it will automatically display in Beijing time.
For example, Douzi wants the time of Sydney to be displayed on the web page, and you can find that the time of the database is UTC time, while the output of the web page is Sydney time.
Settings.py
LANGUAGE_CODE = 'en-us'TIME_ZONE =' Australia/Sydney'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True
Database table
Web page
When defining a field, you need to specify the corresponding parameters in addition to the type. In Django, he provides the following parameters:
Whether null-> db can be empty default-> default primary_key-> primary key db_column-> column name db_index-> index unique-> unique index unique_for_date-> indexing unique_for_month by time-> indexing unique_for_year by month-> by year To index auto_now-> when creating When the time auto_now_add-> update is automatically generated, the drop-down box appears in the current time choices-> django admin Avoid connected tables to query whether blank-> django admin can be empty verbose_name-> django admin display field Chinese editable-> django admin can be edited error_messages-> error message is not help_text-> django admin prompt validators-> django form, custom error message (under)
Please note the use of choice in example 1. The advantage is that for values that do not change much, it is faster to store them directly in memory, while for values that change frequently, we still need to use the database for multi-table queries.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.