Django-1.8.3新建一个简单的News app——02models

现在我们就开始为news建立表啦

打开news/models.py, 把这些都敲下来:

from django.db import models


# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=64)
    reporter = models.ForeignKey('Reporter')
    summary = models.CharField(max_length=256)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)


    def __unicode__(self):
        return self.title


class Reporter(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField(default=18)
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)


    def __unicode__(self):
        return self.name
接下来,大致讲讲这两个class:

Article,继承django内置的models.Model。

  • title, 定义为一个CharField,设定长度64,效果和mysql中的 varchar(64)差不多。
  • reporter, 是一个外键,ForeignKey其实就是many-to-one,多个文章可以对应一个作者。此时里面的参数 Reporter 添加了双引号,是因为Reporter这个class没有在Article之前定义,如果Reporter在Article之前就定义了,可以写作 reporter = models.ForeignKey(Reporter)。
  • summary和content不在细表,二者区别在于是否需要限定长度。
  • pub_date和update_date,都是DateTimeField,
    • auto_now_add=True 是你在建立一个Article实例时,它自动输入建立的当前时间,以后更新也不会再变化。
    • auto_now=True是每次修改,自动更新时间。
  • __unicode__(self),是为了前台展示的时候,方便识别。python 3.x 使用 __str__(self).
Reporter:

  • age是一个整型字段,如果建立Reporter时,没有单独设立age的值,默认18
  • gender,CharField,添加了一个choices,供以选择的是‘Male'和’Female',实际在数据库中存储的是‘M’和’F‘

在我们没有设立主键的情况下,django会为Article和Reporter自动建立一个自动增加的ID主键。

cmd中执行:python manage.py makemigrations news

F:\mysites>python manage.py makemigrations news
Migrations for 'news':
  0001_initial.py:
    - Create model Article
    - Create model Reporter
    - Add field reporter to article
再 python manage.py migrate

F:\mysites>python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, news, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying news.0001_initial... OK
  Applying sessions.0001_initial... OK
然后,我们输入:python manage.py shell,进入shell模式

F:\mysites>python manage.py shell
Python 2.7.10 (default, May 23 2015, 09:44:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from news.models import *
>>> r1 = Reporter(
... name='John Smith',age=20,gender='M')
>>> r1
<Reporter: John Smith>
>>> Reporter.objects.all()
[]
>>>
上面,我们建立了,一个Reporter的实例r1,但是我们发现Reporter.objects.all()返回的是一个空列表。这是因为r1没有save

>>> r1.save()
>>> Reporter.objects.all()
[<Reporter: John Smith>]
r1.save()之后,这个实例才算真正的存储到了Reporter之中了。
我们再继续添加一个Article
>>> Article.objects.create(title='Hello Django',reporter=r1,summary='New in Django 1.7', content='The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list')
<Article: Hello Django>
>>> Article.objects.all()
[<Article: Hello Django>]
这种方式可以直接建立。注意:pub_date 和 update_date,我们并没有设置,他会自动取建立实例的当前时间。
>>> a1 = Article.objects.all()[0]
>>> a1.pub_date
datetime.datetime(2015, 8, 29, 8, 23, 6, 377000, tzinfo=<UTC>)
因为在mysites/mysites/setting.py 的 TIME_ZONE = 'UTC', 我并未对其做任何改变,所以时间比我的实际时间慢了8个小时。当然各位可以设置为‘Asia/Shanghai',或者’Asia/Chongqing'。

最后,我们退出shell模式,在cmd中,输入:python manage.py syncdb

F:\mysites>python manage.py syncdb
d:\python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\management\commands\syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
  warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)

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

You have installed Django's auth system, and don't have any superusers defined.
Would you like to create one now? (yes/no):
然后按照提示,建立出一个superuser。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值