Django

Advanced Django ORM

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

28 perguntas de entrevista·
Senior
1

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

Resposta

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?

Resposta

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?

Resposta

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 perguntas de entrevista

Domine Django para sua proxima entrevista

Acesse todas as perguntas, flashcards, testes tecnicos, exercicios de code review e simuladores de entrevista.

Comece gratis