January 20, 2020

Django Querysets Overview



  • fields and behavior of data
  • maps to a db table
  • subclass of django.db.models.Model
  • attribute represents a db field
  • model provides an automated db access api
  • db-table name is auto derived from metadata
  • id field is auto generated
  • db-backend can be specified in the settings file
  • db-tables are generated during migration
  • fields contain info about type, default html widget, validation
  • field options contain eg nullability and max_length


  • instance of model class represents a row in db-table
  • save() saves model to db (insert). save has no return value
  • foreign keys can be updated like any other field. an object of the right type needs to be assigned
  • retrieve objects with a queryset via a manager on the model class


  • represens a coolection of objects from db
  • the manager of the model is called 'objects' by default. it is accessed via the model class not the instance:
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name='Foo', tagline='Bar')
>>> b.objects
AttributeError: "Manager isn't accessible via Blog instances."
  • refine a queryset with filter or exclude
  • filters can be chained
  • querysets are lazy. only when evaluating django will fire a sql query
  • get retrieves a single row
  • filters can reference fields on the model using the f-expressions
  • querysets are cached upon first retrieval
  • if only a part of the queryset is evaluated, then the cache is not populated. printing does not populate the cache
  • complex queries can be constructed with Q-objects
  • using python slicing on querysets does return an updated queryset