Sobes.tech
Junior — Middle

Can you list different methods of working with QuerySet in Django?

sobes.tech AI

Answer from AI

In Django, a QuerySet is a lazy set of database queries that allows filtering, sorting, and modifying the data selection.

Main methods for working with QuerySet:

  • filter(**kwargs) — filters records based on specified conditions.
  • exclude(**kwargs) — excludes records matching the conditions.
  • all() — returns all records.
  • order_by(*fields) — sorts records by specified fields.
  • values(*fields) — returns a QuerySet of dictionaries with specified fields.
  • values_list(*fields, flat=False) — returns tuples of values of specified fields.
  • get(**kwargs) — returns a single object matching the conditions (raises an exception if none or multiple objects are found).
  • count() — returns the number of records.
  • exists() — checks if records exist.
  • update(**kwargs) — updates fields of selected records.
  • delete() — deletes records.
  • select_related(*fields) — optimizes queries with foreign keys by doing a JOIN.
  • prefetch_related(*fields) — optimizes queries with ManyToMany and reverse relations.

Example:

from myapp.models import Book

books = Book.objects.filter(author='Толстой').order_by('title')
for book in books:
    print(book.title)
Can you list different methods of working with… - sobes.tech