使用pycharm开发web——django2.1.5(三)创建models并进入交互界面shell做一些简单操作

python学习网 2019-06-17 12:15:02

这里model可以认为是数据对象本身

相当于在写java代码时候model目录下创建的实体类,models.py 中可以包含多个实体类,感觉这个操作挺骚的

下面是polls app里面的models,仍然根据刘江老师的网站进行学习,此处不赘述。

models.py

from django.db import models

# Create your models here.
from django.db import models
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

这里的Question 和 Choice 两个类,将来在mysql之中就是两张表,就叫这俩名字!而类中的属性就是字段名即column名

完事之后,请将polls加在settings.py中的INSTALLED_APP列表中,准备迁移。

直接用简写方式就行:

下面在settings.py中

# pysite/settings.py

INSTALLED_APPS = [
'polls',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

好的开始迁移,之前做的迁移是对项目整体迁移,当model有所更新的时候,新的内容需要再次同步

终端运行:

python manage.py makemigrations polls

这时候得到如下提示:

Migrations for 'polls':
  polls/migrations/0001_initial.py:
    - Create model Choice
    - Create model Question

django获得了迁移信息,然后迁移:

python manage.py migrate

看到这样的画面:

python manage.py migrate
Operations to perform:
    Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
    Rendering model states... DONE
    Applying polls.0001_initial... OK

这样来到数据库后,你就发现多了些东西

两张表后缀名是不是似曾相识呢?

没错就是想的那样。

接下来打开进入交互界面中(在终端中):

import django
django.setup()

接下来这段直接拿刘老师写的内容加一些自己的理解粘过来:

 >>> from polls.models import Question, Choice # 导入我们写的模型类
    # 现在系统内还没有questions对象
    >>> Question.objects.all()
    <QuerySet []>

    # 创建一个新的question对象
    # Django推荐使用timezone.now()代替python内置的datetime.datetime.now()
    # 这个timezone就来自于Django的依赖库pytz
    from django.utils import timezone
    >>> q = Question(question_text="What's new?", pub_date=timezone.now())

    # 你必须显式的调用save()方法,才能将对象保存到数据库内
    >>> q.save()

    # 默认情况,你会自动获得一个自增的名为id的主键
    >>> q.id
    1

    # 通过python的属性调用方式,访问模型字段的值
    >>> q.question_text
    "What's new?"
    >>> q.pub_date
    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

    # 通过修改属性来修改字段的值,然后显式的调用save方法进行保存。
  #这里请注意,这种写法实际上是不安全的,因为你不会允许其他人随意更改一个类的属性值,后续应该在models里面将实体类的属性私有化而不是直接这样放,使用get,set方法获取和修改
>>> q.question_text = "What's up?" >>> q.save() # objects.all() 用于查询数据库内的所有questions >>> Question.objects.all() <QuerySet [<Question: Question object>]>

当调用了q.save()之后,来到你的数据库中,这里q是一个Question对象,对应的表polls_question中你会发现表里面多了一条数据,就是你刚才写的。

django在创建表之初会自动创建id主键自增列,所以调用增删改查就不用过多考虑,你默认它(id)存在即可。

对models进行小修改:

models.py

from django.db import models
import datetime
from django.utils import timezone

# Create your models here.
from django.db import models
class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    #toString()方法
    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

然后你重启shell,这时候

>>> import django
>>> django.setup()
>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet [<Question: what's up>]>

,今天上课先写这些喽,继续学习新知识!!

阅读(2310) 评论(0)