In this tutorial we will learn how to query the database. This step is very important and it may be a bit boring but if you understand how to query I database in Django you basically will never have any issues with django.
We will use the django shell to query the database. We will grab post that we already created, create new post and even delete some post so lets get started.
Let's fire up the django shell.
1. python3 manage.py shell
2. Since our post our tied into the user auth framework we will need to query that database as well so we will need to import the data base
'from django.contrib.auth.models import User'. Now we have access to the Users database.
3. Now we want to have access to our post model so we need to import that as well
'from blog.models import Post'
4. Now we want to have access to the Users post so we have to query the database for them.
'user = User.objects.get(username='admin')'
5. Now we want to create a new post.
'post = Post.objects.create(title='third post', slug='third-post', content='third post content', author=user)'
6. Now we have created a new post but we still have to commit it to the database which we will do with a simple onliner.
'post.save()'
7. How to do we get the post.
Post.objects.all()
8. Modify objects
post.title = 'This is a new title'
post.save()
9. Order post in alphabetical order
Post.objects.order_by('title')
order post in reverse order
Post.objects.order_by('-title')
10. delete a post
post = Post.objects.get(id=2)
post.delete()
On this page of the site you can watch the video online Querysets and Django Shell with a duration of hours minute second in good quality, which was uploaded by the user Code master 11 October 2016, share the link with friends and acquaintances, this video has already been watched 9,147 times on youtube and it was liked by 68 viewers. Enjoy your viewing!