属性(Properties)(续)
⚠️ 避免在属性中执行查询
# ❌ 错误:属性中执行数据库查询 class Course(BaseModel): @property def student_count(self) -> int: return self.students.count() # 每次访问都会查询数据库! @property def instructor_name(self) -> str: return self.instructor.full_name # 外键,可能导致 N+1 查询 # ✅ 正确:使用 selector 或在查询时优化 def course_list_with_counts(): return Course.objects.annotate( student_count=Count('students') ).select_related('instructor')