[英]Change representation of Superclass without field depending of Subclass object (__str__)
I am running a django app and have a setup like this:我正在运行一个 django 应用程序并且有这样的设置:
ModelSuper(models.Model):
class Meta:
abstract = False
ModelSub1(ModelA):
name = models.CharField(...)
def __str__:
return self.name
ModelSub2(ModelA)
name = models.CharField(...)
def __str__:
return self.name
ModelForeign(models.Model):
element = models.ForeignKey(ModelA)
def __str__:
return self.name
So ModelForeign
has a FK to ModelSuper
.所以
ModelForeign
有一个 FK 到ModelSuper
。 What happens now is that when I create an instance of ModelForeign
I can choose if it belongs either to ModelSub1
or to ModelSub2
.现在发生的是,当我创建
ModelForeign
的实例时,我可以选择它是属于ModelSub1
还是属于ModelSub2
。 But the string representation is ModelSuper Onject (3)
where (3) is the id.但字符串表示形式是
ModelSuper Onject (3)
,其中 (3) 是 id。
Normally I can change this representation by overwriting the __str__
method on the model, but since I do not have any fields on the Supermodel I can't return anything.通常我可以通过覆盖 model 上的
__str__
方法来更改此表示,但由于我在 Supermodel 上没有任何字段,所以我无法返回任何内容。
What I tried:我尝试了什么:
__str__
method in the Submodels but that does not help.__str__
方法,但这没有帮助。 Also when I do API-calls I get ModelSuper Onject (3)
back instead of a human-readable name.此外,当我进行 API 调用时,我会
ModelSuper Onject (3)
而不是人类可读的名称。
Is there a way to do what I intend to do?有没有办法做我打算做的事? Thanks in advance for help and hints.
在此先感谢您的帮助和提示。 Very much appreciated!
非常感谢!
EDIT1: What I tried thanks to Abdul's help: EDIT1:感谢 Abdul 的帮助,我尝试了什么:
class ModelA(models.Model):
class Meta:
abstract = False
TYPE_CHOICES = [('sub1', 'sub1'), ('sub2', 'sub2')]
type_model = models.CharField(max_length=50, choices=TYPE_CHOICES, null=True, blank=True)
def __str__(self):
if self.type_model == "sub1":
return "sub1"
elif self.type_model == "sub2":
return "sub2"
else:
return "unkown"
I am not understanding how your foreign key works as model inheritance means the tables are separate.我不明白你的外键是如何工作的,因为 model inheritance 意味着表是分开的。 How about trying something like this:-
尝试这样的事情怎么样: -
ModelA(models.Model):
TYPE_CHOICES = [('Sub1', 'ModelSub1'), ('Sub2', 'ModelSub2')]
model_type = models.CharField(max_length=4, choices=TYPE_CHOICES)
def __str__:
# Return string representation using if-else
class Meta:
abstract = False
ModelSub1(ModelA):
name = models.CharField(...)
model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)
def __str__:
return self.name
ModelSub2(ModelA)
name = models.CharField(...)
model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)
def __str__:
return self.name
ModelForeign(models.Model):
element = models.ForeignKey(ModelA)
def __str__:
return self.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.