Brief example
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
The above Person
model will create such a table in the database:
CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
- The name of the table
myapp_person
, is automatically generated based on the metadata model may be overwritten to other names, see the Table names . id
Field is added automatically, but this behavior can be overridden. See auto-increment primary key field .- In this example
CREATE TABLE
SQL statements using PostgreSQL syntax, it should be noted that based on Django settings file to use the appropriate SQL statements database type specified.
After a good django model definition, we need to add applications in settings.py in INSTALLED_APP
models syntax:
Property = models. Field type (field options)
Field Type:
1.BooleanField() True 0,False 1
2.CharField () max_length string length
3.DateField () date type
4.DateTimeField () datetime type
5.DecimalField () decimal type eg: money = models.DecimalField (max_digits = 7, decimal_places = 2) integrally 7, to one decimal place, the integer 5
6.FloatField () float type
7.InterField () int type
8.EmailField () varvhar type
9.URLField () varchar type
10.TextField () text type
11.ImageField () to save the image into the database image = models.ImageField (upload_to = "static / images /")
12.AutoField(primary_key=True) 自增
Field options:
1.primary_key primary key is True, if not specified, Django automatically added
2.unique unique to True
3.default specify a default value
4.null to True to allow empty, the default is False
5.db_index the column index increased to True
6.db_column property is mapped to a table column names
7.blank True, the permit does not fill, the default is False
8.choices option field (enum) choices = two yuan ancestral
Yuan options:
class Meta:
Yuan option = ""
abstract = True This model is an abstract base class
app_label = "" If the model is defined outside of models, tell django, the model belongs to which application
db_table = "" model name of the corresponding data table (the default table name is a name of the application model name _)
ording = [ '- order_date'] is a list of tuples or strings, each string of a field name is preceded by a '-' represents a reverse order, there is no '-' represent positive sequence alignment, using the '? 'Represents a random ordering
ording = [ '- pud_date', 'author'] >> pub_date represented by reverse sort, sort by author positive sequence
verbose_name = "" alias objects, if not set, the class name will open as Django readme name, such as CamelCase becomes camel case
verbose_name_plural verbose_name complex