使用自己的 __str__() 方法而不是通过 Django 访问对象的模型方法。

huangapple go评论81阅读模式
英文:

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&quot;({x}, {y})&quot;
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&#39;s through which I&#39;ve accessed the object?

</details>


# 答案1
**得分**: 0

如果我尝试查询 `Location.objects.get(pk=1)`,我会得到 `&lt;Location object (1)&gt;`,而我期望得到 `(123, 456)`。

Django 不会自动降级,这可能是出于性能原因:它需要对`Place`和`Coordinates`两个表进行`LEFT OUTER JOIN`操作,以确定是哪一个,然后进行一些魔法操作来创建一个`Coordinate`模型。随着子类的增多(包括子子类等),连接操作的数量将会变得庞大,会对性能造成严重的影响。

如果你真的需要这个功能,有一些像 [**`django-polymorphic`**&amp;nbsp;&lt;sup&gt;\[readthedocs\]&lt;/sup&gt;](https://django-polymorphic.readthedocs.io/en/stable/) 这样的包可以实现上面描述的流程,但总的来说,关系数据库不太适合处理继承,因此模型继承通常不是一个好主意。

<details>
<summary>英文:</summary>

&gt; If I try to query `Location.objects.get(pk=1)`, I get `&lt;Location object (1)&gt;`, 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`**&amp;nbsp;&lt;sup&gt;\[readthedocs\]&lt;/sup&gt;](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>



huangapple
  • 本文由 发表于 2023年7月10日 15:04:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76651385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定