Django

Advanced Django ORM

Raw SQL, custom managers, query expressions, database functions, atomic transactions, select_for_update, race conditions, database routers

28 interview questions·
Senior
1

What is the main difference between Model.objects.raw() and connection.cursor() for executing raw SQL in Django?

Answer

Model.objects.raw() returns automatically mapped model instances, preserving ORM benefits like attribute access and relations. connection.cursor() returns a raw database cursor with tuples, offering more flexibility for queries not tied to a specific model, but requiring manual result handling.

2

What is the main advantage of creating a custom Manager in Django rather than adding methods directly to the model?

Answer

A custom Manager encapsulates table-level query logic, allowing method chaining with QuerySets and reusing this logic everywhere the model is used. Model methods operate on individual instances. The Manager also allows modifying the default QuerySet with get_queryset().

3

How to implement a custom QuerySet to enable chaining of custom methods in Django?

Answer

To enable chaining, create a class inheriting from QuerySet with methods returning self or a filtered QuerySet. Then use the custom QuerySet via Manager.from_queryset() or define a custom Manager with get_queryset() returning the custom QuerySet. This allows calling Model.objects.custom_method().filter().

4

Which Django expression to use for atomically incrementing a counter in the database without race condition risk?

5

What is the function of transaction.atomic() and how does it handle exceptions in Django?

+25 interview questions

Master Django for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free