usage of class inheritance in django for polymorphism?
I need your help in the following matter :
in my django models, the following classes exist :
class QItem(models.Model)
class Question(QItem)
class QuestionSet(QItem):
items = models.ManyToManyField(QItem, blank=True, null=True, through='Ordering', related_name="contents")
class Ordering(models.Model):
item = models.ForeignKey(QItem)
qset = models.ForeignKey(QuestionSet, related_name="questionSet")
order = models.IntegerField(unique=True)
So QuestionSet should be able to contain both Question objects, and other QuestionSet objects, in the order specified in Ordering.order.
When performing
o1 = Ordering(item=q, qset=q1)
where q1 is a Question object, I get
ValueError:开发者_StackOverflow社区 Cannot assign "[<Question: q1>]": "Ordering.item" must be a "QItem" instance.
What is the correct way to get this functionality? (to be able to treat both questions and questionsets at the same time?) Is it even possible?
Although I haven't tested it yet, seems that a possible resolution might lie in this :
http://bserve.webhop.org/wiki/django_polymorphic/doc
and it should be as easy as the following (copied from above link for convenience)
from polymorphic import PolymorphicModel
class ModelA(PolymorphicModel):
field1 = models.CharField(max_length=10)
class ModelB(ModelA):
field2 = models.CharField(max_length=10)
class ModelC(ModelB):
field3 = models.CharField(max_length=10)
精彩评论