博客五部曲之三 - 博客RESTful


1446 浏览 5 years, 9 months

8 Python Shell中执行更新和删除

版权声明: 转载请注明出处 http://www.codingsoho.com/

在Python Shell中执行更新和删除

下面通过在python shell执行更新和删除操作帮忙理解一下这两个功能

进入shell命令

python manage.py shell

导入相应的对象,并且获取即将修改的对象

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from posts.models import Post
>>> from posts.api.serializers import PostDetailSerializer
>>> obj = Post.objects.get(id=3)
>>> obj
<Post: new post3>

下面代码会将新的data数据写入当前对象

>>> data = {
...     "title" : "hi, there",
...     "slug": "new-content",
...     "publish": "2018-02-02"
... }
>>> new_item = PostDetailSerializer(obj, data=data)
>>> if new_item.is_valid():
...     new_item.save()
... else:
...     print new_item.errors
...
{'slug': [ErrorDetail(string=u'post with this slug already exists.', code=u'unique')]}
>>>     print new_item.errors
KeyboardInterrupt

出错了,因为这个data数据里的slug跟别的冲突了,修改这个变量,继续执行相同操作。

>>> data = {
...     "title" : "hi, there",
...     "slug": "new-content-new",
...     "publish": "2018-02-02"
... }
>>> new_item = PostDetailSerializer(obj, data=data)
>>> if new_item.is_valid():
...     new_item.save()
... else:
...     print new_item.errors
...
<Post: hi, there3>
>>> new_item.data
{'slug': u'new-content-new', 'publish': '2018-02-02', 'title': u'hi, there'}

上面代码中,id=3的这个对象成功被修改了。

接下来将它删除。

>>> new_item.delete()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'PostDetailSerializer' object has no attribute 'delete'
Serializer没有删除命令,可以用model的delete功能来删除。
>>> obj.delete()
(1, {u'posts.Post': 1})

删除之后,返回一个元组。

>>> obj
<Post: hi, thereNone>
>>> obj = Post.objects.get(id=3)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "E:\Computer\virtualenv\iblog\env\lib\site-packages\django\db\models\query.py", line 379, in get
    self.model._meta.object_name
DoesNotExist: Post matching query does not exist.

查看被删除对象,变量虽然还存在,但是查看数据对象已经不存在了。