Querying the DB in views.py
Querying a database is basically interacting with it in some way.
Importing Models
To interact with the database, we need to import them like so:
In instaclone/views.py:
from database.models import Post, Like
Making Queries
There are three main types of Queries we might want to make:
Retrieve All Items
https://docs.djangoproject.com/en/1.10/topics/db/queries/#retrieving-all-objects
Filter for Some Items
https://docs.djangoproject.com/en/1.10/topics/db/queries/#retrieving-specific-objects-with-filters
Get One Item
https://docs.djangoproject.com/en/1.10/topics/db/queries/#retrieving-a-single-object-with-get
Adding to our Views.py
This is our existing code in views.py
class HomePage(View):
def get(self, request):
# code to query the database goes here!
return render(request, 'index.html')
As we said, however, we want our homepage to show every post that we have. To get a list of every post object in our Post
Table, we can use the following line.
posts = Post.objects.all()
Now, let's add it into our views. Let's access every post and then print out the post's attributes. Change your HomePage get method to reflect the following:
class HomePage(View):
def get(self, request):
# code to query the database goes here!
posts = Post.objects.all()
for post in posts:
print(post.caption)
print(post.postedBy)
print(post.imgURL)
print()
return render(request, 'index.html')