如何使用同一个表创建多个多态Django模型

2024-04-30 20:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在这种情况下,我有一个基本Django模型Rolls,映射到表rolls。有多种类型的转鼓,由一个名为type的列控制。在我正在为(以前是PHP)编写v2的旧代码库中,我为每种类型创建了子类,这些子类控制设置它们自己的type值,效果很好。我不知道如何在Django设置这个

我希望它们都使用相同的表,并且每个表都将从基本模型派生方法,但是对于许多方法有不同的实现。我想我可以编写一个管理器来处理返回正确值的问题,但我不知道如何设置模型

我尝试设置一个单一的基础模型,然后从中派生出其他模型,但这些模型为每个模型创建了不同的表。使用managed = False似乎是错误的,因为子类并不表示它们自己的表


Tags: django方法代码模型类型管理器type情况
1条回答
网友
1楼 · 发布于 2024-04-30 20:36:40

您的做法是正确的,但我相信您想要的是proxy models,而不是非托管的,例如proxy = True

Sometimes, however, you only want to change the Python behavior of a model – perhaps to change the default manager, or add a new method.

This is what proxy model inheritance is for: creating a proxy for the original model. You can create, delete and update instances of the proxy model and all the data will be saved as if you were using the original (non-proxied) model. The difference is that you can change things like the default model ordering or the default manager in the proxy, without having to alter the original.

然后您可以重写每个子类的save方法以设置正确的type,并重写每个子类的默认查询管理器以筛选该type

相关问题 更多 >