Django Learning Diary 03_ Model _fields

Source: Internet
Author: User

Create a model

Model corresponding to the application of the project, a project may contain many applications, through the command

Python startapp MyApp

To create an app called MyApp, Django will help generate the following directories:

? ?
? ?
? ? migrations/
? ? ? ?
? ?
? ?
? ?

Among them, is the place to realize the design of the model.

Python avoids direct manipulation of the database through the construction of the model, and by configuring the database environment, it is not a problem to switch the database without changing the model, not only to facilitate the database upgrade or change, but also to manage the data model conveniently.

According to Djangodocument's guidelines, edit to create a model of person:

Class person (models. Model):
? ? First_Name = models. Charfeild (max_length=30)
? ? Last_Name = models. Charfeild (max_length=30)

The above creates a person model that corresponds to a database and can be seen as creating a form that contains the first name and last name two fields and the Django Auto-created primary key: ID. If you want to specify a primary key instead of an automatically created ID as the primary key, you need to add the property when the Charfeild object is initialized: Primary_key = True.


Fields are the most important part of the model and the body of the data. corresponding to the database, field also has a lot of types, using more than the above example of Charfield to create a character field, Bigintegerfield can create 64-bit maximum shaping field, Textfeild can create a large string field, Binaryfield can create byte-type fields, Booleanfeild can create Boolean fields, and there are Emailfield, Datefield, Timefield, Datetimefield, Ipaddressfield and so on.

In addition to specifying a field type, you need to constrain it by certain attributes. If setting the blank property to True allows the field to be empty, otherwise it is not allowed; You can specify a default value by setting the default property, which will be referenced in all model instances, so it must not be a mutable object (dictionary, list, collection, etc.). Otherwise all instances refer to the same object, which can be imagined to be synchronized, and if a mutable object is needed, it should be wrapped into an executable object, as in the following example, the JSON field will have a dictionary as its default value:

Def contact_feild_default ():
? ? return {' email ': ' [email protected] '}
Contact_info = models. Jsonfield ("ContactInfo", Default=contact_feild_default)

You can change the field to an optional value by specifying the choices property, and the optional value must be iterative:

Province_choices = (
? ? (' ZJ ', ' Zhejiang '),
? ? (' FJ ', ' Fujian '),
? ? (' BJ ', ' Beijing '),
? ? (' SH ', ' Shanghai '),
Address = models. Charfeild (max_length = 3, choices = province_choices,default= ' ZJ ')

Where the first element in the tuple represents what is actually used in the database, and the second element is a name that is easy for the user to understand.

Optional constants are written in the class definition, which makes it easy to manage namespaces, and the second makes it easy to call some constants. In django1.7, the newly added optional mode for grouping

Media_choices = (
? ? (' Audio ', (
? ? ? ? ? ? (' vinyl ', ' vinyl '),
? ? ? ? ? ? (' CD ', ' CD '),
? ? ? ? )
? ? ),
? ? (' Video ', (
? ? ? ? ? ? (' VHS ', ' VHS Tape '),
? ? ? ? ? ? (' DVD ', ' DVD '),
?? ? ? ?)
? ? ),
? ? (' unknown ', ' unknown '),

The grouping pattern can contain ungrouped tuples, the first two groupings, Audio, video for the group, the tuple within the group is the actual value, the second element is a name that is easy for the user to understand.

Django supports relational databases, and you can specify a relational model in field. Specify a foreign key, such as ForeignKey:

Class Car (models. Model):
? ? Manufacturer = Models. ForeignKey (' manufacturer ')
? ? # ...
Class manufacturer (models. Model):
? ? # ...
? ? Pass

Using a string in ForeignKey to represent the model name of the foreign key to be used, Django parses the string and finds the model of the response. If the model is not in the same app, use ForeignKey (' appname. ModelName ') can also be parsed.

You can specify the properties of the foreign key to be constrained, such as related_name,related_query_name,to_field,on_delete, and so on, do not understand how to use, it seems to be bad to fill up the knowledge of the database.

More complex, many-to-many data models can be implemented with foreign keys

Django Learning Diary 03_ Model _fields

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: 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.