Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Fields commonly used in Django model systems and ways to create many-to-many relationships

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "the fields commonly used in the Django model system and the ways to create many-to-many relationships". In the daily operation, it is believed that many people have doubts about the fields commonly used in the Django model system and the way to create many-to-many relationships. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful to answer your doubts about the fields commonly used in the Django model system and the way to create many-to-many relationships. Next, please follow the editor to study!

Common field

AutoField:int self-incrementing column, you must enter the parameter primary_key=True. When there is no self-incrementing column in model, a column named id is automatically created.

IntegerField: an integer type in the range of-2147483648 to 2147483647.

CharField: character type. The max_length parameter must be provided. Max_length represents the character length.

DateField: date field with date format YYYY-MM-DD, which is equivalent to the datetime.date () instance in Python.

DateTimeField: date and time field in the format YYYY-MM-DD HH:MM [: ss [.uuuuuu]] [TZ], which is equivalent to the datetime.datetime () instance in Python.

All fields set AutoField (Field)-int self-incrementing column, must enter parameter primary_key=True BigAutoField (AutoField)-bigint self-increment column, must fill in 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 and self-incrementing column username = models.CharField (max_length=32) class Group (models.Model): # Custom nid = models.AutoField (primary_key=True) Name = models.CharField (max_length=32) SmallIntegerField (IntegerField):-small integers-32768 ~ 32767 PositiveSmallIntegerField (PositiveIntegerRelDbTypeMixin) IntegerField)-positive small integers 0 ~ 32767 IntegerField (Field)-Integer sequence (signed)-2147483648 ~ 2147483647 PositiveIntegerField (PositiveIntegerRelDbTypeMixin) IntegerField)-positive integer 0 ~ 2147483647 BigIntegerField (IntegerField):-long integer (signed)-9223372036854775808 ~ 9223372036854775807 BooleanField (Field)-Boolean type NullBooleanField (Field):-Boolean value 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 Verification Ipv4 and Ipv6-parameters are provided in Django Admin and ModelForm: protocol, used to specify Ipv4 or Ipv6, 'both', "ipv4", "ipv6" unpack_ipv4. If specified as True, it can be resolved to 192.0.2.1 when you enter:: ffff:192.0.2.1. To enable this function, protocol= "both" URLField (CharField)-string type is required. Authentication URL SlugField (CharField)-string type is provided in Django Admin and ModelForm. Authentication is provided in Django Admin and ModelForm to support letter, number, underscore, hyphen (minus) CommaSeparatedIntegerField (CharField)-string type, and the format must be comma-separated numeric UUIDField (Field)-string type. FilePathField (Field)-string that provides validation of UUID format in Django Admin and ModelForm 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 file 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.FileSystemStorage ImageField (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 of uploaded picture (string) height_field=None width of uploaded picture saved database field name (string) DateTimeField (DateField)-date + time format YYYY-MM-DD HH:MM [: ss [.uuuuuuuuu]] [TZ] DateField (DateTimeCheckMixin Field)-date format YYYY-MM-DD TimeField (DateTimeCheckMixin, Field)-time format HH:MM [: ss [.uuuuuu]] DurationField (Field)-long integer Time interval, stored in the database according to bigint. The value obtained in ORM is datetime.timedelta type FloatField (Field)-floating point DecimalField (Field)-decimal-parameter: max_digits, total length of decimal decimal_places Decimal length BinaryField (Field)-correspondence between the binary type ORM field and the actual database field: '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)', field parameter

Null: used to indicate that a field can be empty

Unique: if set to unique=True, this field must be unique in this table.

Db_index: if db_index=True, it represents setting the database index for this field.

Default: sets the default value for this field.

Db_column: sets the field name corresponding to this property in the database table

The following properties can be set for the three time fields DatetimeField, DateField, and TimeField.

Auto_now_add: configure auto_now_add=True to add the current time to the database when creating a data record.

Auto_now: auto_now=True is configured, and this field is updated each time the data record is updated.

For more information on other attributes, please see the official documentation.

Relation field ForeignKey

Foreign key types are used in ORM to represent foreign key associations, and the ForeignKey field is generally set to the 'many' side of 'one-to-many'. ForeignKey can be associated with other tables as well as with itself.

Field parameters:

-to: set the table to be associated-to_field: set the field of the table to be associated-related_name: the field name used in the reverse operation to replace the 'table name _ set' in the original reverse query. Class Classes (models.Model): name = models.CharField (max_length=32) class Student (models.Model): name = models.CharField (max_length=32) theclass = models.ForeignKey (to= "Classes") when we want to query all the students associated with a class (reverse query) We would write: models.Classes.objects.first () .student_set.all () when we add the parameter related_name to the ForeignKey field Class Student (models.Model): name= models.CharField (max_length=32) theclass = models.ForeignKey (to= "Classes", related_name= "students") when we want to query all the students associated with a class (reverse query), we will write: models.Classes.objects.first (). Students.all ()-related_query_name: reverse query operation The connection prefix used to replace the table name. -on_delete: the behavior of the rows associated with the current table when the data in the associated table is deleted. Models.CASCADE: delete associated data, associated with it also delete models.DO_NOTHING: delete associated data, raise error IntegrityError models.PROTECT: delete associated data, raise error ProtectedError models.SET_NULL: delete associated data, set the associated value to null (if the FK field needs to be set to nullable) models.SET_DEFAULT: delete associated data The value associated with it is set to the default value (provided that the FK field needs to set the default value) models.SET: delete the associated data, a. The value associated with it is set to the specified value, setting: models.SET (value) b. The value associated with it is set to the return value of the executable object Setting: models.SET (executable object) def func (): return 10 class MyModel (models.Model): user = models.ForeignKey (to= "User", to_field= "id" On_delete=models.SET (func))-db_constraint: whether to create a foreign key constraint in the database. Default is True. OneToOneField

One-to-one field. One-to-one fields are usually used to extend existing fields.

Example:

Class Author (models.Model): name = models.CharField (max_length=32) info = models.OneToOneField (to='AuthorInfo') class AuthorInfo (models.Model): phone = models.CharField (max_length=11) email = models.EmailField ()

Field parameters:

To: sets the table to be associated

To_field: sets the field to be associated.

On_delete: same as ForeignKey field.

ManyToManyField

The relationship is established through the third table in the database.

Field parameters:

To: sets the table to be associated

Related_name: same as ForeignKey field.

Related_query_name: same as ForeignKey field.

Symmetrical: a field that specifies whether to create a reverse operation internally only when many-to-many self-association. The default is True.

For example: class Person (models.Model): name = models.CharField (max_length=16) friends = models.ManyToManyField ("self") at this point, the person object has no person_set attribute. Class Person (models.Model): name = models.CharField (max_length=16) friends = models.ManyToManyField ("self", symmetrical=False) at this point, the person object can now be reverse queried using the person_set property.

Through: when using the ManyToManyField field, Django automatically generates a table to manage many-to-many associations. But we can also manually create a third table to manage many-to-many relationships, so we need to specify the table name of the third table through through.

Through_fields: sets the associated field.

Db_table: the name of the table in the database when the third table is created by default.

Three ways to create many-to-many relationships

Method 1: create the third table yourself

Class Book (models.Model): title = models.CharField (max_length=32, verbose_name= "title") class Author (models.Model): name= models.CharField (max_length=32, verbose_name= "author's name") # create the third table yourself Through the foreign key association book and the author class Author2Book (models.Model): author = models.ForeignKey (to= "Author") book = models.ForeignKey (to= "Book") class Meta: unique_together = ("author", "book")

Method 2: create the third table automatically through ManyToManyField

Class Book (models.Model): title = models.CharField (max_length=32, verbose_name= "title") # automatically create the third table class Author (models.Model) through the ManyToManyField included with ORM: name= models.CharField (max_length=32, verbose_name= "author name") books = models.ManyToManyField (to= "Book", related_name= "authors")

Method 3: set up ManyTomanyField and specify the third table created by yourself

Class Book (models.Model): title = models.CharField (max_length=32, verbose_name= "title") # create the third table yourself and specify the association class Author (models.Model) through ManyToManyField: name= models.CharField (max_length=32, verbose_name= "author name") books = models.ManyToManyField (to= "Book", through= "Author2Book", through_fields= ("author", "book") # through_fields accepts a 2-tuple ('field1' 'field2'): # where field1 is the name of the model foreign key that defines the ManyToManyField (author), and field2 is the foreign key name of the associated target model (book). Class Author2Book (models.Model): author = models.ForeignKey (to= "Author") book = models.ForeignKey (to= "Book") class Meta: unique_together = ("author", "book")

Note: when we need to store additional fields in the third relational table, we use the third approach.

Meta information

The corresponding class of ORM contains another Meta class, while the Meta class encapsulates some database information. The main fields are as follows:

Db_table: ORM's table name in the database is the app_ class name by default, and the table name can be overridden through db_table.

Index_together: Federated index

Unique_together: Federated unique index

Ordering: specifies which field to sort by default. Only when this property is set can the result of our query be reverse ().

At this point, the study of "fields commonly used in Django model systems and ways to create many-to-many relationships" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report