我想在django管理程序中显示一个模型,但是使用逻辑来选择要显示的两个模型。
目前的执行情况:
模型
class User(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=30, blank=True)
class ExpectedNames(User):
class Meta:
proxy=True`管理员
@admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created'
我想做的是:#像这样的事情
模型
class User(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=30, blank=True)
class User2(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=30, blank=True)
class ExpectedNames(User):
class Meta:
proxy=True
if name == "Rick":
return User
else:
return User2管理员
@admin.register(ExpectedNames) class ExpectedNamesAdmin(admin.ModelAdmin): date_hierarchy = 'created'
任何建议都不能确定这是否是正确的做法。
发布于 2019-07-15 21:11:41
我认为这是不可能的,因为它在Django文档中指出:
基类限制:代理模型必须从一个非抽象模型类继承。您不能从多个非抽象模型继承,因为代理模型不能在不同数据库表中的行之间提供任何连接。代理模型可以继承任意数量的抽象模型类,只要它们不定义任何模型字段。代理模型还可以继承共享公共非抽象父类的任意数量的代理模型。
https://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models
发布于 2020-02-18 10:59:33
在同样的情况下,我使用新的魔法方法。
我有带有字段document_type的模型文档。如果document_type是‘合同’,我想要ContractProxy,如果‘要约’- OfferProxy。为此,我创建了新的代理:
class RelatedDocumentProxy(Document):
class Meta:
proxy = True
def __new__(cls, *args, **kwargs):
doc_type = args[1]
if doc_type == 'contract':
return ContractProxy(*args, **kwargs)
return OfferProxy(*args, **kwargs)
document_type是第一个字段,它将首先传递给方法。
https://stackoverflow.com/questions/54565493
复制相似问题