Skip to content

Instantly share code, notes, and snippets.

@dmmeteo
Last active December 3, 2022 14:48
Show Gist options
  • Save dmmeteo/8950ce8a6fbf08c63f411ec5f5c8b199 to your computer and use it in GitHub Desktop.
Save dmmeteo/8950ce8a6fbf08c63f411ec5f5c8b199 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