Django创建第一个应用

一.创建第一个应用,并在settings.py中添加。

python manage.py startapp article

 

二.创建第一个模型

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField()
    pub_date = models.DateTimeField('date published')
    likes = models.IntegerField()

    def __unicode__(self):
        return self.title

Field Types 和 Field Options:

>>> import re                  #右边为手动添加非代码部分
>>> for fieldtype in dir(models):
...     if re.search('Field', fieldtype):
...         print fieldtype
...                   #对应默认的HTML         #特有的选项
AutoField                                                    
BigIntegerField
BooleanField
CharField               <input type='text' ...>    max_length必须指定
CommaSeparatedIntegerField
DateField
DateTimeField            <input type='text' ...>
DecimalField
EmailField
Field
FieldDoesNotExist
FileField
FilePathField
FloatField
GenericIPAddressField
IPAddressField
ImageField
IntegerField              <input type='text' ...>
ManyToManyField
NullBooleanField
OneToOneField
PositiveIntegerField
PositiveSmallIntegerField
SlugField
SmallIntegerField
TextField               <textarea>...</textarea>
TimeField
URLField

Field Options公共选项:

  • null:If True, Django will store empty values as NULL in the database. Default is False.
  • blank:If True, the field is allowed to be blank. Default is False.
  • primary_key:If True, this field is the primary key for the model.
  • unique:If True, this field must be unique throughout the table.
  • default:The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
  • choices:An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. If this is given, the default form widget will be a select box instead of the standard text field and will limit choices to the choices given.
  • ...

Model Methods:

__unicode__():

>>> from article.models import Article
>>> Article.objects.all()
[<Article: test 1>, <Article: test 2>, <Article: test 3>, <Article: TestTitle>, <Article: FileTest>]
>>> 

详细请看:https://docs.djangoproject.com/en/1.5/ref/models/fields/

 

三.同步到后台,创建数据库表

yang@mint-linux ~/Documents/sinaapp/yangqiong/1 $ python manage.py sql article
BEGIN;
CREATE TABLE `article_article` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `title` varchar(200) NOT NULL,
    `body` longtext NOT NULL,
    `pub_date` datetime NOT NULL,
    `likes` integer NOT NULL
)
;

COMMIT;
yang@mint-linux ~/Documents/sinaapp/yangqiong/1 $ python manage.py syncdb

 

posted @ 2013-09-02 21:16  杨琼  阅读(397)  评论(0编辑  收藏  举报