我正在使用Django 1.6并且代码与此类似:
class Message (models.Model):
message_type = models.CharField(max_length=1)
class MessageA (Message):
some_field_for_a = models.CharField(max_length=1)
class MessageB (Message):
some_field_for_b = models.CharField(max_length=1)
我想将新消息保存到数据库,如下所示:
message_a = MessageA()
message_a.save()
但是对于当前的实现,我需要像这样明确地声明message_type
:
message_a = MessageA()
message_a.message_type = "A"
message_a.save()
这显然违反直觉,因为MessageA
默认情况下应该message_type = "A"
。是否有任何 Django方式避免此样板代码并自动为每个继承的类设置message_type
(请记住,field hiding is not permitted和覆盖__init__
也应该避免)?