
本文探讨 django 中 question 模型的合理设计方式,重点解决「必选类型 + 可选子类型」的层级关系建模问题,提出去冗余外键、安全字符串表示、清晰语义表达等优化方案。
在构建教育类或题库系统时,常需对题目进行多级分类:例如「数学 → 代数 → 一元二次方程」或「物理 → 力学 → 牛顿第二定律」。此时,QuestionType(如“数学”)作为顶层分类,QuestionSubType(如“代数”)作为其下属细分,而题目本身只需关联到最细粒度的 QuestionSubType 即可——因为子类型已天然携带其所属类型信息。因此,原始模型中同时保留 type(ForeignKey to QuestionType)和 type_subtype(ForeignKey to QuestionSubType)两个字段,不仅造成数据冗余,还引入一致性风险(如 subtype 所属 type 与独立 type 字段不一致)。
✅ 推荐优化方案如下:
-
移除冗余外键
删除 Question.type 字段,仅保留 type_subtype(建议重命名为更语义化的 subtype):class Question(QuestionAbstractModel): chapter = models.ForeignKey(Chapter, blank=True, null=True, on_delete=models.CASCADE) subtype = models.ForeignKey( QuestionSubType, on_delete=models.SET_NULL, # 推荐使用 SET_NULL 而非 CASCADE,避免误删 subtype 导致题目丢失 blank=True, null=True, related_name='questions' ) solution_url = models.URLField(max_length=555, blank=True) -
强化子类型模型的语义表达
在 QuestionSubType 中显式暴露所属类型,并优化 __str__ 方法,使其返回完整路径(如 "数学 → 代数"):class QuestionSubType(models.Model): question_type = models.ForeignKey(QuestionType, on_delete=models.CASCADE, related_name='subtypes') question_sub_type = models.CharField(max_length=255) def __str__(self): return f"{self.question_type.question_type} → {self.question_sub_type}" class Meta: verbose_name = "题目子类型" verbose_name_plural = "题目子类型" -
安全、健壮的 __str__ 实现
原始写法 f"{self.chapter.subject.grade}..." 在 chapter 或其关联字段为 None 时将抛出 AttributeError。应始终做空值检查,并提供降级显示:def __str__(self): # 构建章节描述(支持空值) if self.chapter and self.chapter.subject: chapter_str = f"{self.chapter.subject.grade} {self.chapter.subject.name} {self.chapter.name}" else: chapter_str = "未指定章节" # 构建类型描述(利用已优化的 QuestionSubType.__str__) subtype_str = str(self.subtype) if self.subtype else "无类型归属" return f"[{chapter_str}] {subtype_str}" -
额外建议:添加数据库约束与查询便利性
- 在 QuestionSubType 上添加 unique_together = ('question_type', 'question_sub_type') 防止重复子类型;
- 为 subtype 字段添加 db_index=True(Django 2.0+ 默认启用,但显式声明更清晰);
- 如需按主类型快速筛选题目,可通过反向关系:Question.objects.filter(subtype__question_type__question_type="数学")。
? 总结:良好的 Django 模型设计应遵循「单一事实来源」原则——子类型已蕴含类型信息,无需重复存储;同时,所有涉及外键链式访问的字符串表示、序列化逻辑,都必须主动防御 None 值。这样既提升数据一致性,又增强代码鲁棒性与可维护性。










