博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用pycharm开发web——django2.1.5(三)创建models并进入交互界面shell做一些简单操作...
阅读量:4604 次
发布时间:2019-06-09

本文共 7546 字,大约阅读时间需要 25 分钟。

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

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

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

models.py

from django.db import models# Create your models here.from django.db import modelsclass 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.pyINSTALLED_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 migrateOperations to perform:    Apply all migrations: admin, auth, contenttypes, polls, sessionsRunning migrations:    Rendering model states... DONE    Applying polls.0001_initial... OK

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

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

没错就是想的那样。

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

import django
django.setup()

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

>>> from polls.models import Question, Choice # 导入我们写的模型类    # 现在系统内还没有questions对象    >>> Question.objects.all()    
# 创建一个新的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=
) # 通过修改属性来修改字段的值,然后显式的调用save方法进行保存。   #这里请注意,这种写法实际上是不安全的,因为你不会允许其他人随意更改一个类的属性值,后续应该在models里面将实体类的属性私有化而不是直接这样放,使用get,set方法获取和修改 >>> q.question_text = "What's up?" >>> q.save() # objects.all() 用于查询数据库内的所有questions >>> Question.objects.all()
]>

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

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

对models进行小修改:

models.py

from django.db import modelsimport datetimefrom django.utils import timezone# Create your models here.from django.db import modelsclass 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()
]>

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

于是我又回来了

使用其它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() 
]> >>> Question.objects.filter(id=1)
]> >>> Question.objects.filter(question_text__startswith='What')
>>> Question.objects.filter(question_text__startswith='What')
>>> Question.objects.filter(question_text__startswith="What's")
>>> Question.objects.filter(question_text__startswith='what')
]> >>> from django.utils import timezone File "
", 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.objects.get(id=2) Traceback (most recent call last): File "
", line 1, in
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)
>>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>> q.choice_set.all()
>>> q.choice_set.create(choice_text='Not much',votes=0)
>>> q.choice_set.create(choice_text='The sky',votes=0)
>>> c = q.choice_set.create(choice_text='Just hacking again',votes=0) >>> c.question
>>> q.choice_set.all()
,
,
]> >>> q.choice_count() Traceback (most recent call last): File "
", line 1, in
AttributeError: 'Question' object has no attribute 'choice_count' >>> q.choice_set.count() 3 >>> Choice.objects.filter(question__pub_date__year=current_year)
,
,
]> >>> c = q.choice_set.filter(choice_text__startwith'Just hacking') File "
", 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 "
", line 1, in
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 "
", line 1, in
AttributeError: 'QuerySet' object has no attribute 'objects' >>> c.all()
>>> q.choice_set.all()
,
]>

 

 

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

你可能感兴趣的文章
【WEB前端经验之谈】时间一年半,或沉淀、或从零开始。
查看>>
优云软件助阵GOPS·2017全球运维大会北京站
查看>>
linux 装mysql的方法和步骤
查看>>
poj3667(线段树区间合并&区间查询)
查看>>
51nod1241(连续上升子序列)
查看>>
SqlSerch 查找不到数据
查看>>
集合相关概念
查看>>
Memcache 统计分析!
查看>>
(Python第四天)字符串
查看>>
个人介绍
查看>>
使用python动态特性时,让pycharm自动补全
查看>>
MySQL数据库免安装版配置
查看>>
你必知必会的SQL面试题
查看>>
html5 Canvas绘制时钟以及绘制运动的圆
查看>>
Unity3D热更新之LuaFramework篇[05]--Lua脚本调用c#以及如何在Lua中使用Dotween
查看>>
JavaScript空判断
查看>>
洛谷 P1439 【模板】最长公共子序列(DP,LIS?)
查看>>
python timeit
查看>>
Wireless Network 并查集
查看>>
51nod 1019 逆序数
查看>>