Skip to content

Instantly share code, notes, and snippets.

@AVIPAGHADAR1729
Created February 21, 2022 05:53
Show Gist options
  • Select an option

  • Save AVIPAGHADAR1729/d5011b033bc6977cf2e56fcd8994cbb1 to your computer and use it in GitHub Desktop.

Select an option

Save AVIPAGHADAR1729/d5011b033bc6977cf2e56fcd8994cbb1 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