![](/img/trans.png)
[英]Is it possible to subclass the immutable date class and override the __str__ method?
[英]How to apply __str__ method to subclass of abstract superclass class
我有3個模型,其中一個是Abstract超類,其中兩個是該超類的子類。
我正在嘗試在模型上實現一個簡單的str方法,但是無論實現如何都會引發此錯誤:
TypeError: __str__ returned non-string (type NoneType)
這是我的模型:
class DemandBase(models.Model):
demand = models.FloatField(blank=True, null=True)
building = models.ForeignKey(Building, on_delete=models.CASCADE)
class Meta:
abstract = True
class DemandHeat(DemandBase):
def __str__(self):
return str(self.id)
class DemandCool(DemandBase):
def __str__(self):
return str(self.id)
好的,所以我嘗試像上面的示例中那樣進行強制轉換,但是我也嘗試了以下操作但未成功:
return "This is an example {}".format(self.demand)
和這個
return f"This is an example {self.demand}"
和這個:
return "this is a string"
所有這些替代方法都可以在普通模型上使用,但是在這里卻沒有,所以我認為它與類的繼承或抽象有關。
非常感謝任何幫助或提示。 提前致謝!
編輯:當我嘗試在管理員中創建新的BuildingGroup時,也會收到此錯誤。 它還具有作為m2m關系的建築物的ForeignKey。 該模型如下所示:
class BuildingGroup(models.Model):
description = models.CharField(max_length=500, null=True, blank=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
buildings = models.ManyToManyField(Building, default=None, blank=True)
def __str__(self):
return self.description
我無法重現您的錯誤。
如下所示,遷移運行正常:
example/migrations/0001_initial.py
- Create model DemandCool
- Create model DemandHeat
我正在使用Django == 2.2.3
編寫了相同的模型,但不包括ForeignKey(完全沒有區別)
例如/ models.py
1 from django.db import models
2
3
4 class DemandBase(models.Model):
5 demand = models.FloatField(blank=True, null=True)
6
7 class Meta:
8 ┆ abstract = True
9
10
11 class DemandHeat(DemandBase):
12
13 def __str__(self):
14 ┆ return str(self.id)
15
16
17 class DemandCool(DemandBase):
18
19 def __str__(self):
20 ┆ return str(self.id)
21
python manage.py shell
Python 3.6.8 (default, Jan 14 2019, 11:02:34)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from example.models import DemandHeat
>>> instance = DemandHeat(demand=0.7)
>>> instance.save()
>>> instance.__str__()
'1'
>>> print(instance)
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.