Django ORM and QuerySets

Django simplifies the task of interacting with the databases by using ORM (Object Relational Mapper). You can write universal database queries with simple QuerySets.

Whaht is QuerySet

A Queryset is simply a list of objects from the Django Models. It can be used to query data as Create, Filter, Update, Order etc. Queryset can be written in Django Shell or in views.py.

python manage.py shell

For example, to get all data from the model Blog under app named myapp, run:

    >>> from myapp.models import Blog
    >>> Post.objects.all()
    QuerySet ['my blog title', ...]
                                

Popular Django QuerySets

Create

ModelName.objects.create(fieldname=value)

Select

ModelName.objects.all()

Filter

ModelName.objects.filter(fieldname=value)

Exclude

ModelName.objects.exclude(fieldname=value)

Ordering

ModelName.objects.all().order_by('field_name')