我试图在数据库中保存一种内容表结构。简单的例子:Django - 检查多表继承查询集的类型
models.py
class Section (models.Model):
title = models.CharField(max_length=80)
order = models.IntegerField()
class SectionClickable(Section):
link = models.CharField(max_length=80)
class SectionHeading(Section):
background_color = models.CharField(max_length=6)
views.py
sections = Section.objects.filter(title="Hello!")
for section in sections:
if(section.sectionheading):
logger.debug("It's a heading")
我需要做一些处理操作,如果它是一个SectionHeading
实例,但(如Django的手册),访问如果对象不是类型SectionHeading,则section.sectionheading
将引发DoesNotExist错误。
我一直在寻找这类问题的替代品,并且我正在浏览contenttypes包中的通用外键。但是,这似乎会在Django Admin方面造成更多麻烦。任何人都可以提供比上述更好的解决方案吗?
编辑:由于order
字段,我避免了抽象继承。我将不得不在两个查询集连接在一起,并通过订单
你怎么关联'Section's和'SectionHeading's? – second
SectionHeading是Section – bcoughlan
的子类啊,道歉,没注意 – second