DEV Community

Cover image for Django ORM
Odipo Otieno
Odipo Otieno

Posted on • Updated on

Django ORM

Django provides an Object-Relational Mapping (ORM) layer that allows you to interact with your database using Python code instead of writing raw SQL queries. The ORM provides a high-level, Pythonic API for performing database operations. Here are some common Django ORM commands and their equivalent SQL statements:

  1. Creating Objects:

    • Django ORM: Model.objects.create(**kwargs)
    • SQL: INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)
  2. Saving Objects:

    • Django ORM:
    • SQL: UPDATE table_name SET column1=value1, column2=value2, ... WHERE condition
  3. Querying Objects:

    • Django ORM: Model.objects.all()
    • SQL: SELECT * FROM table_name
  4. Filtering Objects:

    • Django ORM: Model.objects.filter(**kwargs)
    • SQL: SELECT * FROM table_name WHERE condition
  5. Ordering Objects:

    • Django ORM: Model.objects.order_by(*fields)
    • SQL: SELECT * FROM table_name ORDER BY column1, column2, ...
  6. Updating Objects:

    • Django ORM: Model.objects.filter(**kwargs).update(**update_kwargs)
    • SQL: UPDATE table_name SET column1=value1, column2=value2, ... WHERE condition
  7. Deleting Objects:

    • Django ORM: object.delete()
    • SQL: DELETE FROM table_name WHERE condition

These are just a few examples of how Django ORM commands correspond to SQL statements. The Django ORM handles many more complex operations, such as complex filtering, grouping, and aggregations, while abstracting away the underlying SQL syntax.

Top comments (0)