Skip to content

Instantly share code, notes, and snippets.

@benjackson33
Created December 5, 2023 07:06
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 benjackson33/0b4184ea879f6d7919038f73d895b63f to your computer and use it in GitHub Desktop.
Save benjackson33/0b4184ea879f6d7919038f73d895b63f to your computer and use it in GitHub Desktop.
Django ORM cheat sheet

Django ORM Cheat Sheet

Querying Data

Retrieving Objects

  • Model.objects.all(): Retrieve all objects in the model.
  • Model.objects.get(): Retrieve a single object that matches the query.
  • Model.objects.filter(): Retrieve objects that match the specified lookup parameters.
  • Model.objects.exclude(): Retrieve objects that do not match the specified lookup parameters.

Chaining Querysets

  • filter().exclude(): Chain filters and exclusions together.
  • filter().filter(): Chain multiple filters together.
  • annotate(): Add annotations to the queryset.
  • order_by(): Sort the queryset based on specified fields.
  • values(): Return a QuerySet of dictionaries instead of model instances.
  • distinct(): Return distinct results for a queryset.

Field Lookups

  • exact, iexact: Exact match (case-sensitive, case-insensitive).
  • contains, icontains: Case-sensitive, case-insensitive containment test.
  • ... (other field lookups)

Modifying Data

Creating Objects

  • Model.objects.create(): Create a new object and save it to the database.
  • object.save(): Save changes to an existing object.

Updating Objects

  • object.save(): Save changes to an existing object.
  • Model.objects.update(): Update multiple objects at once.
  • update_or_create(): Update an existing object or create a new one.

Deleting Objects

  • object.delete(): Delete a single object.
  • Model.objects.filter().delete(): Delete multiple objects matching a filter.

Aggregation

  • aggregate(): Perform aggregate functions on a queryset (e.g., Sum, Count, Avg).

Relationships

  • Access related objects through object attributes (related_name, related_query_name).
  • Use double underscores for traversing relationships in queries (e.g., related_model__field).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment