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

这里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>]>

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

于是我又回来了

使用其它api

 
Question.objects.filter(question_text__startswith='What')

 

这里是区分大小写的,What !=what

 
(venv) D:\pysite>python manage.py shell
 Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
 Type "help", "copyright", "credits" or "license" for more information.
 (InteractiveConsole)
 >>>
 >>>
 >>> from polls.models import Question, Choice
 >>> Question.objects.all()
 <QuerySet [<Question: what's up>]>
 >>> Question.objects.filter(id=1)
 <QuerySet [<Question: what's up>]>
 >>> Question.objects.filter(question_text__startswith='What')
 <QuerySet []>
 >>> Question.objects.filter(question_text__startswith='What')
 <QuerySet []>
 >>> Question.objects.filter(question_text__startswith="What's")
 <QuerySet []>
 >>> Question.objects.filter(question_text__startswith='what')
 <QuerySet [<Question: what's up>]>
 >>>  from django.utils import timezone
   File "<console>", line 1
     from django.utils import timezone
     ^
 IndentationError: unexpected indent
 >>> from django.utils import timezone
 >>> current_year = timezone.now().year
 >>> Question.objects.get(pub_date__year=current_year)
 <Question: what's up>
 >>> Question.objects.get(id=2)
 Traceback (most recent call last):
   File "<console>", line 1, in <module>
   File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho
 d
     return getattr(self.get_queryset(), name)(*args, **kwargs)
   File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\query.py", line 408, in get
     self.model._meta.object_name
 polls.models.Question.DoesNotExist: Question matching query does not exist.
 >>> Question.objects.get(pk=1)
 <Question: what's up>
 >>> q = Question.objects.get(pk=1)
 >>> q.was_published_recently()
 True
 >>> q.choice_set.all()
 <QuerySet []>
 >>> q.choice_set.create(choice_text='Not much',votes=0)
 <Choice: Not much>
 >>> q.choice_set.create(choice_text='The sky',votes=0)
 <Choice: The sky>
 >>> c =  q.choice_set.create(choice_text='Just hacking again',votes=0)
 >>> c.question
 <Question: what's up>
 >>> q.choice_set.all()
 <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
 >>> q.choice_count()
 Traceback (most recent call last):
   File "<console>", line 1, in <module>
 AttributeError: 'Question' object has no attribute 'choice_count'
 >>> q.choice_set.count()
 3
 >>> Choice.objects.filter(question__pub_date__year=current_year)
 <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
 >>> c = q.choice_set.filter(choice_text__startwith'Just hacking')
   File "<console>", line 1
     c = q.choice_set.filter(choice_text__startwith'Just hacking')
                                                                ^
 SyntaxError: invalid syntax
 >>> c = q.choice_set.filter(choice_text__startwith='Just hacking')
 Traceback (most recent call last):
   File "<console>", line 1, in <module>
   File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho
 d
     return getattr(self.get_queryset(), name)(*args, **kwargs)
   File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\query.py", line 892, in filter
     return self._filter_or_exclude(False, *args, **kwargs)
   File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\query.py", line 910, in _filter_or_exc
 lude
     clone.query.add_q(Q(*args, **kwargs)) 
  File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\sql\query.py", line 1290, in add_q 
    clause, _ = self._add_q(q_object, self.used_aliases) 
  File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\sql\query.py", line 1318, in _add_q 
    split_subq=split_subq, simple_col=simple_col, 
  File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\sql\query.py", line 1251, in build_fil 
ter 
    condition = self.build_lookup(lookups, col, value) 
  File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\sql\query.py", line 1110, in build_loo 
kup 
    lhs = self.try_transform(lhs, lookup_name) 
  File "D:\pysite\mysite\venv\lib\site-packages\django\db\models\sql\query.py", line 1151, in try_trans 
form 
    "permitted%s" % (name, output_field.__name__, suggestion) 
django.core.exceptions.FieldError: Unsupported lookup 'startwith' for CharField or join on the field no 
t permitted, perhaps you meant startswith or istartswith? 
>>> c = q.choice_set.filter(choice_text__startswith='Just hacking') 
>>> c.delete() 
(1, {'polls.Choice': 1}) 
>>> c.objects.all() 
Traceback (most recent call last): 
  File "<console>", line 1, in <module> 
AttributeError: 'QuerySet' object has no attribute 'objects' 
>>> c.all() 
<QuerySet []> 
>>> q.choice_set.all() 
<QuerySet [<Choice: Not much>, <Choice: The sky>]>

 

转载于:https://www.cnblogs.com/lovely-lisk/p/11037911.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值