使用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>]>
创建超级用户,就管理员
(venv) D:\pysite>python manage.py createsuperuser
Username (leave blank to use 'lisk'): admin
Email address: lsk@admin.com
Password:
Password (again):
Superuser created successfully.
新的pysite/urls.py
"""pysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('polls/', include('polls.urls')),
#为了安全起见将admin页面地址改为control/
path('control/', admin.site.urls),
]
启动服务,然后去127.0.0.1:8000/control/
就可以看到登陆页面
然后在admin.py中注册polls应用
from django.contrib import admin
from .models import Question
admin.site.register(Question)
之后说就是这样的效果
这里的history可以查看操作历史
使用pycharm开发web——django2.1.5(三)创建models并进入交互界面shell做一些简单操作的更多相关文章
- 使用pycharm开发web——django2.1.5(四)视图和模板相关
刘老师说这块很重要..... 应该是很重要,大概看了一下,这里面关于views中函数作用,大概看来可能就是相应请求,传入数据和跳转,基本功能上貌似这些框架都差不多吧(其实我并没用过3个框架以上.... ...
- 使用pycharm开发web——django2.1.5(二)创建一个app并做一些配置
这里我学习的呢是刘江老师的站,主要原因在于他这个版本新,还比较细节 网址先留一手,约等于在引用http://www.liujiangblog.com/ 开始正题: 1.在pycharm界面终端命令行里 ...
- 使用pycharm开发web——django2.1.5(一)入坑尝试第一步,基本搭建
首先,接触python的人应该都会用pip 来安装需要的包吧(------>>>>)默认 在运行中使用python -m django --version来检查自己的djang ...
- 使用pycharm开发web——django2.1.5(五)表单和通用视图
看了刘江老师教程这么多天,卧槽,我才发现他也曾跻身于行伍之间,interesting 刘老师这波讲解很到位,告诉你如何编写单例视图的时候忽然告诉你,其实不用这么麻烦,我们有通用视图,那些总是要做相似的 ...
- SSM框架开发web项目系列(三) MyBatis之resultMap及关联映射
前言 在上篇MyBatis基础篇中我们独立使用MyBatis构建了一个简单的数据库访问程序,可以实现单表的基本增删改查等操作,通过该实例我们可以初步了解MyBatis操作数据库需要的一些组成部分(配置 ...
- Python全栈开发之路 【第三篇】:Python基础之字符编码和文件操作
本节内容 一.三元运算 三元运算又称三目运算,是对简单的条件语句的简写,如: 简单条件语句: if 条件成立: val = 1 else: val = 2 改成三元运算: val = 1 if 条件成 ...
- 4.菜鸟教你一步一步开发 web service 之 axis 客户端创建
转自:https://blog.csdn.net/shfqbluestone/article/details/37723517 在上个教程中我们创建了一个 axis 服务端的 web service ...
- web前端学习(三)css学习笔记部分(3)-- css常用操作
5. CSS常用操作 5.1 对齐 使用margin属性进行水平对齐 <!DOCTYPE html> <html lang="en"> <head ...
- (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作
上午写了下单向循环链表的程序,今天下午我把双向链表的程序写完了.其实双向链表和单向链表也是有很多相似的地方的,听名字可以猜到,每个节点都包含两个指针,一个指针指向上一个节点,一个指针指向下一个节点.这 ...
随机推荐
- luogu 2114 [NOI2014]起床困难综合症 位运算+贪心
感觉这个思路非常巧妙啊~ code: #include <bits/stdc++.h> #define ll long long #define setIO(s) freopen(s&qu ...
- 快速幂 x
快速幂! 模板如下: #include<iostream> #include<cmath> #include<cstdio> #define LL long lon ...
- 删除git中无用的大文件
推荐阅读:为什么你的 Git 仓库变得如此臃肿 有时候我们不小心提交了一些大文件上去,后来删除了,但是已经于事无补了,整个git的提及已经蹭蹭上去了. 这个时候怎么办呢? 1. 查看有哪些大文件(to ...
- Js 之复制到剪贴板 clipboard.js
一.下载 https://github.com/zenorocha/clipboard.js/archive/master.zip 二.Demo示例 <!DOCTYPE html> < ...
- php-fpm脚本
#! /bin/sh ### BEGIN INIT INFO # Provides: php-fpm # Required-Start: $remote_fs $network # Required- ...
- Qt for Android (二) Qt打开android的相册
以下有一个可以用的Demo https://files.cnblogs.com/files/wzxNote/Qt-Android-Gallery-master.zip 网盘地址: https://pa ...
- mysql 使用service mysqld start 提示未识别服务 进入/etc/rc.d/init.d 下面未发现有mysqld解决方法
1.执行whereis mysql会有如下打印: mysql: /usr/bin/mysql /usr/lib64/mysql /usr/include/mysql /usr/share/mysql ...
- Airbnb新用户的民宿预定结果预测
1. 背景 关于这个数据集,在这个挑战中,您将获得一个用户列表以及他们的人口统计数据.web会话记录和一些汇总统计信息.您被要求预测新用户的第一个预订目的地将是哪个国家.这个数据集中的所有用户都来自美 ...
- 《你不知道的JavaScript(上)》笔记——作用域闭包
当函数可以记住并访问所在的词法作用域时, 就产生了闭包, 即使函数是在当前词法作用域之外执行. function wait(message) { setTimeout( function timer( ...
- Jenkins 自动化部署上线
转载于互联网 jenkins自动化部署项目,通过jenkins 部署来节省运维时间,不需要手动cp上线及版本发布 Jenkins 自动化部署上线 Jenkins Jenkins 自动化部署上线一.Je ...