Using Django Queryset
Django Querysey
### Running shell
```bash
python3 manage.py shell
```
It will oppen command line. Before using QuerSet, you need to import your model here
```bash
from .models import Task
```
## QuerySet
```python
from django.shortcuts import render, get_object_or_404,
from .models import Task
task_list = Task.objects.all()
task = get_object_or_404(Task, title="some title")
task_list = Task.objects.filter(date_created__year=2022)
```
## Simple where clause
```python
Task.objects.filter(title="First Task")
Task.objects.exclude(title="John")
# These two are same
Task.objects.filter(title="First Task")
Task.objects.all().filter(title="First Task")
```
## AND Clause
```python
Dog.objects.create(name='Max', data=None)
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
#This is same as
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
```
## OR Clause
```python
User.objects.filter(first_name="John") | User.objects.filter(first_name="Jane")
```
## Select Query with where clause
```python
Entry.objects.get(headline__contains='Lennon')
Task.objects.filter(title__startswith="First")
Task.objects.all().filter(title__endswith="Task")
Entry.objects.filter(pub_date__lt='2006-01-01')
Entry.objects.filter(pub_date__lte='2006-01-01')
Entry.objects.filter(mod_date__gt='2006-01-01')
Entry.objects.filter(mod_date__gte='2006-01-01')
```
## Limiting the outset
```python
Entry.objects.all()[:5]
```
This post is written by Pravin
Share it :