ORM为数据库建模带来了便利。
https://docs.djangoproject.com/en/dev/topics/db/models/
https://docs.djangoproject.com/en/dev/ref/models/fields/#model-field-types
例如下列定义会自动生成SQL语句:
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL );
常见字段域
AutoField
(
**options
)
BigIntegerField([**options])
BooleanField(**options)
CharField(max_length=None[, **options])
CommaSeparatedIntegerField(max_length=None[, **options])
DateField
(
[
auto_now=False
,
auto_now_add=False
,
**options
]
)
DateTimeField([auto_now=False, auto_now_add=False, **op
tions
]
)
DecimalField(max_digits=None, decimal_places=None[, **options])
EmailField([max_length=75, **options])
FileField(upload_to=None[, max_length=100, **options])
FloatField([**options])
ImageField(upload_to=None[, height_field=None, width_field=None, max_length=100, **options])
IntegerField([**options])
IPAddressField([**options])
TextField([**options])
TimeField([auto_now=False, auto_now_add=False, **options])
URLField([max_length=200, **options])
字段域的参数(options)
null 是否可以为null
blank 是否可以为空
default 缺省值
choices 枚举类型
class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN) def is_upperclass(self): return self.year_in_school in (self.JUNIOR, self.SENIOR)
primary_key 是否为主键。如果不指定主键,会自动生成id字段作为主键。
unique 是否唯一
unique_for_date 是否对日期唯一
validator 指定验证器
verbose_name 更友好的显示名称(注意,django/admin 用到的是覆盖后的model.Model.__unicode__()方法)
关系字段域
外键:
class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer') # ... class Manufacturer(models.Model): # ...多对多:
class Topping(models.Model): # ... class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping)多对多间接关系(注意 Person和Group不是直接关联的,而是通过 through='Membership'):
class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64)
>>> ringo = Person.objects.create(name="Ringo Starr") >>> paul = Person.objects.create(name="Paul McCartney") >>> beatles = Group.objects.create(name="The Beatles") >>> m1 = Membership(person=ringo, group=beatles, ... date_joined=date(1962, 8, 16), ... invite_reason= "Needed a new drummer.") >>> m1.save() >>> beatles.members.all() [<Person: Ringo Starr>] >>> ringo.group_set.all() [<Group: The Beatles>] >>> m2 = Membership.objects.create(person=paul, group=beatles, ... date_joined=date(1960, 8, 1), ... invite_reason= "Wanted to form a band.") >>> beatles.members.all() [<Person: Ringo Starr>, <Person: Paul McCartney>]
# THIS WILL NOT WORK >>> beatles.members.add(john) # NEITHER WILL THIS >>> beatles.members.create(name="George Harrison") # AND NEITHER WILL THIS >>> beatles.members = [john, paul, ringo, george]