2018-12-16 shell

2019-10-04  本文已影响0人  Jackie119

Create object

python manage.py shell

The above command can get into python.

>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='admin')
>>> post = Post(title='Another post',
                          slug='another-post',
                          body='Post body.',
                          author=user)
>>> post.save()

the above code has the similar effect as floowing:

Post.objects.create(title='One more post', slug='one more post', body = 'Post body.', author = user)

Update objects

post.title = 'New Title'
post.save

a object is a record in fact. save method perform update SQL

Retrieving objects

>>> all_posts = Post.objects.all()
>>>  for i in all_posts: print(i.title)

Filter and Order

>>> Post.objects.filter(publish__year=2017)
>>> Post.objects.filter(publish__year=2018,author__username='Mary')
>>>Post.objects.filter(publish__year=2018).exclude(title__startswith='One')  #exclude method.
>>>Post.objects.order_by('title')   #ascending
>>>Post.objects.order_by('-title')  #descending

Delete

>>> post=Post.objects.get(id=1)
>>> post.delete()
上一篇 下一篇

猜你喜欢

热点阅读