Django

Advanced Django ORM

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

28 câu hỏi phỏng vấn·
Senior
1

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

Câu trả lời

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?

Câu trả lời

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?

Câu trả lời

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 câu hỏi phỏng vấn

Nắm vững Django cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí