Django18初体验


1224 浏览 5 years, 3 months

9 模型 Models

版权声明: 转载请注明出处 http://www.codingsoho.com/

参考

定义Model

Django的数据库模型层用了很多ORM (Object-Relational Mapper)

Rich Field Types
类型 说明
CharField和TextField 用的最多的field,它们有很多的相似处,都用于储存文本。CharField 有限定的长度, TextField的长度本质上是不受限制的,依赖于你的需求和数据库的效率
EmailField, URLField, 和IPAddressField 本质上是CharField,增加了额外的验证。
BooleanField 和 NullBooleanField BooleanField用的比较多,用于存储True和False,但有的时候你可能在存储时还不有知道它的值,这时你可能会考虑用Empty或者Null来代替,NullBooleanField正是用于这种需求。
FileField FileField是最复杂的Field之一,因为它的大部分工作都根本不在数据库。跟FilePathField类似,FileField只存储文件路径,但是它还有上传文件和存储到服务器上某个位置的功能。
from django.db import models

# Create your models here.
class SignUp(models.Model):
    email = models.EmailField()
    full_name = models.CharField(max_length=120, blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self): #Python 3.3 is __str__
        return self.email

SignUp从django.db.models.Model继承。这类是Model的标准基类,是django强大的ORM系统的核心。

创建表 - migrate database

makemigrations : 初始化migrations
migrates : 实际运行migrations并且存储到database

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py makemigrations

Migrations for 'newsletter':
  0001_initial.py:
    - Create model SignUp

调用该命令后,django会轮询INSTALLED_APPS里面的app的models.py文件,对于它找到每一个model都会创建一个数据库表(有一些例外: There are exceptions to this later when we get into fancy stuff such as many-to-many relations, but it’s true for this example. If you are using SQLite, you also notice the django.db database file is created exactly where you specified.)

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py migrate

Operations to perform:
  Synchronize unmigrated apps: staticfiles, admindocs, messages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, newsletter
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying newsletter.0001_initial... OK

如果不做修改重新执行该命令,将显示No migrations to apply

(trydjango18) D:\virtualdir\trydjango18\src>python manage.py migrate

Operations to perform:
  Synchronize unmigrated apps: staticfiles, admindocs, messages
  Apply all migrations: sessions, admin, sites, auth, contenttypes, newsletter
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  No migrations to apply.