Python Web framework: Django Model basics, pythondjango

Source: Internet
Author: User
Tags timedelta

Python Web framework: Django Model basics, pythondjango

Model is a single, definite source of information about your data. It contains the basic fields and actions of the data you are storing. Django provides structured data processing and Operation Processing for your network applications through the abstract model layer (models). Database-related code is generally written in models. in py, Django supports databases such as sqlite3, MySQL, and PostgreSQL, and adds, deletes, modifies, and queries databases using database APIs.

You only need to configure which database to use in settings. py, for example:

<1> sqlite:Django uses the sqlite database by default. By default, it comes with the sqlite database driver. Engine name: django. db. backends. sqlite3

<2> mysql:Engine name: django. db. backends. mysql

<3> to change the database:

1 DATABASES = {2 'default': {3 'engine': 'django. db. backends. mysql ', 4'name': 'books', # Your database NAME 5 'user': 'root', # Your database username 6 'Password ':'', # Your Database Password is 7'host': '', # Your Database HOST. The default value is localhost 8 'Port': '123 ', # Your Database port 9} 10 11}
View Code

Note:

1 NAME is the NAME of the database. The database must have been created before mysql is connected, and the database under the above sqlite database. sqlite3 is the project automatically created 2 USER and PASSWORD are respectively the database USER name and PASSWORD. 3. Activate mysql before starting our Django project. 4. Then, when you start the project, an error will be reported: no module named MySQLdb5. This is because django imports the driver MySQLdb by default, but MySQLdb has a major problem with py3, therefore, the driver we need is PyMySQL6 7. Therefore, we only need to find _ init __in the project name file and write: 8 import pymysql9 pymysql. install_as_MySQLdb ()
View Code

Model Field

1 AutoField IntegerField automatically increases according to the actual ID. you usually do not need to use it directly; 2 if not specified, a primary key field will be automatically added to the 3 BigIntegerField you created with a 64-bit integer, the default form component similar to the field IntegerField is a TextInput. 4 5 IntegerField ([** options]) 6 is an integer. In all the databases supported by Django, values in the range from-2147483648 to 2147483647 are valid. The default form input tool is TextInput. 7 8 BinaryField, which is used to store the original binary code. Only bytes assignment is supported. Note that this Field has only limited functions. 9 For example, it is unlikely to query the 10 BooleanField true/false field on the data of a BinaryField value. The default form pendant is a CheckboxInput.11. If you need to set a null value, use NullBooleanField instead of BooleanField. 12 if Field. default is not specified, the default value of BooleanField is None. 13 CharField: a place that stores strings of various lengths from small to large. 14 if it is a huge text type, you can use TextField.15, the default form style of this field is TextInput.16 CharField must receive an additional parameter: 17 CharField. max_length limit: Maximum length of a field. max_length will play a role in the database layer and Django form verification, used to limit the length of a field. 18 DateField this is a datetime using Python. date indicates the date of the instance. there are several additional parameters: 19 20 DateField. auto_now automatically sets this field to the current time each time an object is saved. 21 is the timestamp used for "last modification. Note that it always uses the current date; it is not just a default value, you can overwrite it. 22 23 DateField. auto_now_add cursor automatically sets the current time when the object is created for the first time. The timestamp used for the Creation Time. 24 it always uses the current date; it is different from the default value that you can override. 25 26 by default, the form control corresponding to this field is a TextInput. A calendar control written in JavaScript, 27, and a "Today" shortcut are added to the Administrator site. contains an additional invalid_date error message key. 28 29 30 DateTimeField (DateField)-date + time format YYYY-MM-DD HH: MM [: ss [. uuuuuuu] [TZ] 31 32 DateField (DateTimeCheckMixin, Field)-Date Format YYYY-MM-DD33 34 TimeField (DateTimeCheckMixin, Field)-time format HH: MM [: ss [. uuuuuu] 35 36 DurationField (Field) is used to store the Field type for a period of time-similar to timedelta in Python. 37-long integer, time interval, in the database according to the bigint Storage, the value obtained in the orm is datetime. timedelta type 38 39 DecimalField (max_digits = None, decimal_places = None [, ** options]) indicates a decimal floating point number 40 41 EmailField ([max_length = 254, ** options]) A CharField is used to check whether the entered email address is valid. It uses EmailValidator to verify the validity of the input. 42 43 FileField ([upload_to = None, max_length = 100) is a field used to upload files. 44 The FileField field does not support the primary_key and unique parameters. If it is used, a TypeError is generated. 45 46 FilePathField (path = None [, match = None, recursive = False, max_length = 100]) 47. The content of a CharField is limited to the file name under a specific directory in the file system. There are three parameters, the first of which is required: 48 49 FloatField ([** options]) represents a floating point number using a Python float instance. 50 51 52 ImageField ([upload_to = None, height_field = None, width_field = None, max_length = 100, ** options]) 53 inherits all attributes and methods of FileField, however, the uploaded object is also verified to ensure that it is a valid image.54 55 TextField ([** options]) large text field. The default form component of this model is Textarea. 56 57 TimeField ([auto_now = False, auto_now_add = False, ** options]) refers to the 58 time field, which is the same as datetime. time in Python. Accept the same auto-fill option as DateField. 59. The default format is TextInput. input box. 60 61 URLField ([max_length = 200, ** options]) A CharField type URL. The default form widget for this field is TextInput. 62 63 UUIDField ([** options]) is a field used to store UUID. Use the UUID class of Python. 64 when a PostgreSQL database is used, the Data Type in the database corresponding to this field type is uuid
View Code Field options -- Parameters
1 Field. null if True, Django stores NULL values in the database as null. The default value is False. 2 3 if Field. blank is True, the Field can be blank. The default value is False. 4 5 Field. choices is an iterative structure (such as A list or tuples). 6 is composed of iteratable binary groups (such as [(A, B), (, b)...]), used to provide selection items for this field. 7 if choices is set, the default table style will display the selection box instead of the standard text box, and the option of this selection box is the tuples in choices. 8 9 Field. db_column indicates the name of the Field. If this parameter is not specified, Django uses the Field name as the Field name. 10 11 Field. db_index. If the value is True, django-admin sqlindexes will output the create index statement for this Field. 12 13 14 Field. error_messages allows you to overwrite the default error message. Specify the key to confirm the error message you want to rewrite. 15 16 if Field. primary_key is True, this Field becomes the primary key Field of the model. 17 if you do not specify primary_key = True on any model field, Django will automatically add an AutoField field to act as the primary key. 18 19 if Field. unique is True, this Field must have a unique value in the Table. 20 21 Field. unique_for_month is similar to unique_for_date, except that the Field is unique for the month. 22 23 validators 24 Field. validators a list of Validator fields to be run.
View Code

Meta-define the metadata of the model using the internal class Meta

from django.db import modelsclass Ox(models.Model):horn_length = models.IntegerField()class Meta:ordering = ["horn_length"]verbose_name_plural = "oxen"

The model metadata is "any data that is not a field", such as ordering, db_table, or a human-readable singular and plural name (verbose_name and verbose_name_plural ).

Adding class Meta to the model is completely optional and all options are not required.

Link Field

The power of relational databases is the association between tables.

Django provides three common database relationships: one-to-one, one-to-one, and one-to-one ).
Multi-to-one relationship
Django uses django. db. models. ForeignKey to define multiple-to-one relationships. Similar to other field types: include it as a class attribute in the model.
ForeignKey requires a location parameter: the class associated with the model.

1 limit_choices_to when this field is rendered using a model form or Admin (by default, all objects in the query set can be used), 2 sets an available option for this field. It can be a dictionary, a Q object, or a callable object that returns a dictionary or Q object. 3 Q (caption = 'root ') 4 db_constraint = True # whether to create a foreign key constraint in the database 5 parent_link = False # Whether to display associated data 6 7 related_name in Admin is used to retrieve the source object from the associated object. It is also the default value of related_query_name (the name used when the associated model is used for reverse filtering ). 8 9 related_query_name is used for reverse filtering of the target model. If related_name is set, the default value is its value. Otherwise, the default value is the field name of the associated object associated with the model name 10 11 to_field. By default, Django uses the primary key of the associated object. 12 13 db_constraint controls whether to create constraints for this foreign key in the database. The default value is True14 15 on_delete. When an object referenced by ForeignKey is deleted, Django simulates the constraints of SQL ON DELETE CASCADE by default and deletes the object containing the ForeignKey. This behavior can be changed by setting the on_delete parameter. 16 17 CASCADE deletion; default value. 18 19 PROTECT throws ProtectedError to prevent the deletion of referenced objects. It is a subclass of django. db. IntegrityError. 20 21 SET_NULL: Set ForeignKey to null. If the null parameter is True, this can be done. 22 23 SET_DEFAULT ForeignKey is set to its default value. In this case, the default parameter of ForeignKey must be set. 24 25 SET () SET ForeignKey to the value passed to SET (). If it is a callable object, it is the result after the call. 26. DO_NOTHING does not take any action. If the back-end of your database forcibly references integrity, it will trigger an IntegrityError, unless you manually add an on delete constraint to the database automatically
View Code

ManyToManyField is a multi-to-Multiple Association.

Requires a keyword parameter: the class associated with the model, which works exactly the same way as ForeignKey, including recursive and inert relationships.
Associated objects can be added, deleted, and created through the RelatedManager field.

1 If the source model and target are different, the following field is generated: 2 id: Primary Key of the link. 3 <containing_model> _ id: Declares the model id of the ManyToManyField. 4 <other_model> _ id: id of the model pointed to by the ManyToManyField field. 5 6 if the source model of ManyToManyField is the same as the target model, the following field is generated: 7 id: Primary Key of the link. 8 from _ <model> _ id: id of the source model instance. 9 to _ <model> _ id: id of the Target model instance. 10 This class allows a given model to query associated records as a common model. 11 12 to, # Name of the table to be joined 13 related_name = None, # field name used in reverse operation, used to replace [Table name_set] such as: obj. table name_set. all () 14 related_query_name = None, # The Connection prefix used in the reverse operation to replace the [Table name], such as models. userGroup. objects. filter (Table name__ field name = 1 ). values ('table name__ field name') 15 16 limit_choices_to = None, # conditions provided when the associated data is displayed in Admin or ModelForm: 17 # example: 18-limit_choices_to = {'nid _ gt ': 5} 19-limit_choices_to = lambda: {'nid _ gt': 5} 20 21 from django. db. models import Q22-limit_choices_to = Q (nid _ gt = 10) 23-limit_choices_to = Q (nid = 8) | Q (nid _ gt = 10) 24-limit_choices_to = lambda: Q (nid = 8) | Q (nid _ gt = 10) & Q (caption = 'root') 25 26 minutes rical = None, # When used only for multi-to-Multi-Self Association, reverse rical is used to specify whether to create reverse operation field 27 # When performing the following operations, different reverse rical will have different optional fields 28 models. BB. objects. filter (...) 29 30 # optional fields: code, id, m131 class BB (models. model): 32 33 code = models. charField (max_length = 12) 34 m1 = models. manyToManyField ('self ', required rical = True) 35 36 # optional fields include bb, code, id, m1_class BB (models. model): 38 39 code = models. charField (max_length = 12) 40 m1 = models. manyToManyField ('self ', wrong rical = False) 41 42 through = None, # When customizing the third table, use the field to specify the relational table 43 through_fields = None, # When customizing the third table, fields are used to specify those fields in the relational table for multiple-to-multiple relationship Tables 44 from django. db import models45 46 class Person (models. model): 47 name = models. charField (max_length = 50) 48 49 class Group (models. model): 50 name = models. charField (max_length = 128) 51 members = models. manyToManyField (52 Person, 53 through = 'Membership ', 54 through_fields = ('group', 'person'), 55) 56 57 class Membership (models. model): 58 group = models. foreignKey (Group, on_delete = models. CASCADE) 59 person = models. foreignKey (Person, on_delete = models. CASCADE) 60 inviter = models. foreignKey (61 Person, 62 on_delete = models. CASCADE, 63 related_name = "membership_invites", 64) 65 invite_reason = models. charField (max_length = 64) 66 67 db_constraint = True, # whether to create a foreign key constraint in the database 68 db_table = None, # The name of the table in the database when the third table is created by default
View CodeOneToOneField

One-to-one association. In terms of concept, this field seems to have set unique = True for ForeignKey. The difference is that it will directly return a single object on the other side of the link.

Its primary purpose is to serve as the primary key to expand from another model. For example, multi-Table inheritance is implemented by adding an implicit one-to-one association to the submodel.

A location parameter is required: The class associated with the model. It works in exactly the same way as ForeignKey, including all options related to recursive and inert relationships.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.