<p>我还没有找到一个“干净”或“优雅”的方法来做到这一点。当我遇到这个问题时,我通过欺骗Python解决了这个问题。</p>
<pre><code>class Check(models.Model):
check_type = models.CharField(max_length=10, editable=False)
type = models.CharField(max_length=10, null=True, choices=TYPES)
method = models.CharField(max_length=25, choices=METHODS)
'More fields.'
def __init__(self, *args, **kwargs):
super(Check, self).__init__(*args, **kwargs)
if self.check_type:
map = {'TypeA': Check_A,
'TypeB': Check_B,
'TypeC': Check_C}
self.__class__ = map.get(self.check_type, Check)
def run(self):
'Do the normal stuff'
pass
class Check_A(Check):
class Meta:
proxy = True
def run(self):
'Do something different'
pass
class Check_B(Check):
class Meta:
proxy = True
def run(self):
'Do something different'
pass
class Check_C(Check):
class Meta:
proxy = True
def run(self):
'Do something different'
pass
</code></pre>
<p>它不是真的干净,但它是最容易找到的黑客解决了我的问题。</p>
<p>也许这对你有帮助,也许没有</p>
<p>我也希望其他人能有一个更像Python的解决办法来解决这个问题,因为我一直在数着直到这个方法失败并回来困扰我的日子。。</p>