我有一些类看起来像这样:
class Base:
subs = [Sub3,Sub1]
# Note that this is NOT a list of all subclasses!
# Order is also important
class Sub1(Base): pass
class Sub2(Base): pass
class Sub3(Base): pass
...
Run Code Online (Sandbox Code Playgroud)
现在,这失败了,因为Base.subs时没有定义Sub1和Sub3.但显然我不能把子类放在Base之前.有没有办法在Python中转发声明类?我想使用,isinstance因此subs中的类型实际上必须与后面声明的子类相同,它们具有相同的名称和其他属性是不够的.
一个解决方法是:Base.subs = [Sub3,Sub1] 在定义了子类之后,但我不喜欢以这种方式拆分我的类.
编辑:添加了有关订单的信息
我的Discount模型描述了系统中所有类型折扣的常用字段.我有一些代理模型描述了用于计算总数的具体算法.基Discount类有一个名为的成员字段type,它是一个标识其类型及其相关类的字符串.
class Discount(models.Model):
TYPE_CHOICES = (
('V', 'Value'),
('P', 'Percentage'),
)
name = models.CharField(max_length=32)
code = models.CharField(max_length=32)
quantity = models.PositiveIntegerField()
value = models.DecimalField(max_digits=4, decimal_places=2)
type = models.CharField(max_length=1, choices=TYPE_CHOICES)
def __unicode__(self):
return self.name
def __init__(self, *args, **kwargs):
if self.type:
self.__class__ = getattr(sys.modules[__name__], self.type + 'Discount')
super(Discount, self).__init__(*args, **kwargs)
class ValueDiscount(Discount):
class Meta:
proxy = True
def total(self, total):
return total - self.value
Run Code Online (Sandbox Code Playgroud)
但我继续得到AttributeError的例外,说自己没有类型.如何解决这个问题还是有另一种方法来实现这一目标?
我有一系列看起来像这样的模型:
class Analysis(models.Model):
analysis_type = models.CharField(max_length=255)
def important_method(self):
...do stuff...
class SpecialAnalysis(Analysis):
class Meta:
proxy = True
def important_method(self):
...something different...
Run Code Online (Sandbox Code Playgroud)
这都非常标准.但是,我想要做的是Analysis根据analysis_type字段的值自动将模型转换为代理模型.例如,我希望能够编写如下代码:
>>> analysis = Analysis.objects.create(analysis_type="nothing_special")
>>> analysis.__class__
<class 'my_app.models.Analysis'>
>>> analysis = Analysis.objects.create(analysis_type="special")
>>> analysis.__class__
<class 'my_app.models.SpecialAnalysis'>
>>> analysis = Analysis.objects.get(pk=2)
>>> analysis.__class__
<class 'my_app.models.SpecialAnalysis'>
>>> # calls the ``important_method`` of the correct model
>>> for analysis in Analysis.objects.all():
... analysis.important_method()
Run Code Online (Sandbox Code Playgroud)
这甚至可以远程实现吗?这里提出了一个类似的问题,它实际上为迭代示例提供了一些代码,但是它仍然存在如何从其父代获取或创建代理类实例的问题.我想我可以覆盖一堆管理器方法,但我觉得必须有更优雅的方法来实现它.
我有以下型号.如何从Entity表中访问继承表(Team和Athete)的unicode?我正在尝试显示所有显示"名称"的实体的列表,如果Team和'firstname'和'lastname',如果运动员.
class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
Run Code Online (Sandbox Code Playgroud)