
Advanced Django ORM
Raw SQL, custom managers, query expressions, database functions, atomic transactions, select_for_update, race conditions, database routers
1What is the main difference between Model.objects.raw() and connection.cursor() for executing raw SQL in Django?
What is the main difference between Model.objects.raw() and connection.cursor() for executing raw SQL in Django?
回答
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.
2What is the main advantage of creating a custom Manager in Django rather than adding methods directly to the model?
What is the main advantage of creating a custom Manager in Django rather than adding methods directly to the model?
回答
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().
3How to implement a custom QuerySet to enable chaining of custom methods in Django?
How to implement a custom QuerySet to enable chaining of custom methods in Django?
回答
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().
Which Django expression to use for atomically incrementing a counter in the database without race condition risk?
What is the function of transaction.atomic() and how does it handle exceptions in Django?
+25 面接問題