英文:
Use own __str__() method instead of model's through which object was accessed in Django
问题
我有这样的模型:
```python
class Location(models.Model):
pass
class Place(Location):
name = models.CharField(...)
def __str__(self):
return str(self.name)
class Coordinates(Location):
x = models.DecimalField(...)
y = models.DecimalField(...)
def __str__(self):
return f"({x}, {y})"
如果我尝试查询 Location.objects.get(pk=1).__str__()
,我得到的是 Location object (1)
,但我希望得到 (123, 456)
。
我如何让对象使用它们自己的 __str__()
方法,而不是通过我访问对象的模型来调用该方法?
<details>
<summary>英文:</summary>
I have such models:
class Location(models.Model):
pass
class Place(Location):
name = models.CharField(...)
def __str__(self):
return str(self.name)
class Coordinates(Location):
x = models.DecimalField(...)
y = models.DecimalField(...)
def __str__(self):
return f"({x}, {y})"
If I try to query ```Location.objects.get(pk=1).__str__()```, I get ```Location object (1)```, instead I expect ```(123, 456)```.
How can I make objects to use their own ```__str__()``` method, instead of model's through which I've accessed the object?
</details>
# 答案1
**得分**: 0
如果我尝试查询 `Location.objects.get(pk=1)`,我会得到 `<Location object (1)>`,而我期望得到 `(123, 456)`。
Django 不会自动降级,这可能是出于性能原因:它需要对`Place`和`Coordinates`两个表进行`LEFT OUTER JOIN`操作,以确定是哪一个,然后进行一些魔法操作来创建一个`Coordinate`模型。随着子类的增多(包括子子类等),连接操作的数量将会变得庞大,会对性能造成严重的影响。
如果你真的需要这个功能,有一些像 [**`django-polymorphic`**&nbsp;<sup>\[readthedocs\]</sup>](https://django-polymorphic.readthedocs.io/en/stable/) 这样的包可以实现上面描述的流程,但总的来说,关系数据库不太适合处理继承,因此模型继承通常不是一个好主意。
<details>
<summary>英文:</summary>
> If I try to query `Location.objects.get(pk=1)`, I get `<Location object (1)>`, instead I expect `(123, 456)`.
Django does not automatically downcast, likely for performance reasons: it would mean it has to make `LEFT OUTER JOIN`s to the tables of both `Place` and `Coordinates`, to see which one it is, and then do some magic to create a `Coordinate` model instead. As the number of subclasses grows (including grandchildren, etc.), the amount of `JOIN`s will become huge, with a severe performance penalty.
If you really want this, there are packages like [**`django-polymorphic`**&nbsp;<sup>\[readthedocs\]</sup>](https://django-polymorphic.readthedocs.io/en/stable/) that implement the flow described above, but in general relational databases are just not good with inheritance, and therefore model inheritance is often not a good idea anyway.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论