loading...
Cover image for 👨‍💻 Queries in Django ( Part 7 ) - Django For Beginners

👨‍💻 Queries in Django ( Part 7 ) - Django For Beginners

ketanip profile image KetanIP Originally published at ketaniralepatil.com ・2 min read

This is part of the series Django For Beginners we are going to see about apps in app and we will see about models in django in this part.

In this post we are going to learn a lot queries in django. I recommend you to read last post so as it will be easy to understand context of this post , now let's get started.

These are the models which we are going to use for most part in this post,

from django.db import models
from django.utils import timezone
from djnago.contrib.auth.models import User

class Post(models.Model)
    title = models.CharField(max_length=250)
    created_at = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name="author")
    likes =  models.ManyToManyField(User, blank=True, related_name="likes")
    dislikes =  models.ManyToManyField(User, blank=True, related_name="dislikes")
    likes_count = models.PositiveIntegerField(default=0)
    dislikes_count = models.PositiveIntegerField(default=0)
    rating = models.DecimalField(max_digits=4, decimal_places=2)


class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    liked_posts = models.ManyToManyField(Post, blank=True, related_name="liked_posts")
    disliked_posts = models.ManyToManyField(Post, blank=True, related_name="disliked_posts")


Enter fullscreen mode Exit fullscreen mode

Get All

To get all data of the model we use this query, it is not used most often as it costs a lot of resources if data is large and it is always a good practice to limit the query results which we will see how to do after this,

all_posts = Post.objects.all()
Enter fullscreen mode Exit fullscreen mode

syntax = ModelName.objects.all()

Limit Query Results

To limit results of any query we add [ start_count : end_count ] to get results from start_count and end_count you can also use [ : end_count ] to get results from 0 to end_count. Let's see an example,

only_five_posts = Post.objects.all()[:4]
Enter fullscreen mode Exit fullscreen mode

The above query will give 5 results only as index start from 0 and till 4 it would be five results.

Get Query

There is situation many times when we want to retrieve only one result from the query with exact match of fields for such situations we use get query, let me show you an example,

one_post = Post.objects.get(id=1)
Enter fullscreen mode Exit fullscreen mode

syntax = ModelName.objects.get( pass_keyword_arguments )

Sorry to interrupt you but I want to tell you one thing that I have started a small blog you may continue reading it here it will help me a lot.

Discussion

pic
Editor guide
Collapse
ayaofficielle profile image
ayaofficielle

Very useful 💙

Collapse
ketanip profile image
KetanIP Author

Thank You.