Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hossainchisty/2b85f71a7f393be56d98e655b2321810 to your computer and use it in GitHub Desktop.
Save hossainchisty/2b85f71a7f393be56d98e655b2321810 to your computer and use it in GitHub Desktop.

Cheatsheet for Django QuerySets

Current Django Version: 2.2

Methods that return new QuerySets

Can be chained:

Entry.objects.filter(**kwargs).exclude(**kwargs).order_by(**kwargs)

Methods that do not return QuerySets

Field lookups

Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods filter(), exclude() and get().

Example: Entry.objects.get(id__exact=14)  # note double underscore.

Protip: Use in to avoid chaining filter() and exclude()

Entry.objects.filter(status__in=['Hung over', 'Sober', 'Drunk'])

Aggregation functions

Query-related classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment