简体   繁体   English

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

[英]How can I create multiple polymorphic Django models using the same table

I've got a situation where I have one base Django model Rolls , mapped to the table rolls .我有一种情况,我有一个基础 Django model Rolls ,映射到 table rolls There are multiple types of rolls, controlled by a column called type .有多种类型的卷,由名为type的列控制。 In the older codebase I'm writing a v2 for (used to be PHP), I created subclasses for each type, that controlled setting their own type value, and it worked fine.在较旧的代码库中,我正在为(曾经是 PHP)编写一个 v2,我为每种类型创建了子类,控制设置它们自己的type值,并且工作正常。 I can't figure out how to set this up in Django.我不知道如何在 Django 中进行设置。

I'd like them all to use the same table, and each will derive methods from the base model, but have different implementations for many of those methods.我希望它们都使用同一个表,并且每个都将从基础 model 派生方法,但是对于其中许多方法有不同的实现。 I figure I can write a manager to handle getting back the right values, but I can't figure out how to setup the models.我想我可以写一个管理器来处理取回正确的值,但我不知道如何设置模型。

I tried setting a single base model and then derived other models from it, but those created different tables for each of them.我尝试设置一个单一的基础 model,然后从中派生出其他模型,但这些模型为每个模型创建了不同的表。 Using managed = False seems the wrong way to go, given the subclasses don't represent tables of their own.考虑到子类不代表它们自己的表,使用managed = False似乎是 go 的错误方法。

You're on the right track, but I believe you want proxy models and not unmanaged ones, eg proxy = True :你在正确的轨道上,但我相信你想要代理模型而不是非托管模型,例如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.但是,有时您只想更改 model 的 Python 行为 - 可能是更改默认管理器,或添加新方法。

This is what proxy model inheritance is for: creating a proxy for the original model.这就是代理 model inheritance 的用途:为原始 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.您可以创建、删除和更新代理 model 的实例,所有数据都将像使用原始(非代理)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.不同之处在于您可以更改默认 model 排序或代理中的默认管理器等内容,而无需更改原始内容。

Then you could override each subclass' save method to set the correct type , and each subclass' default query manager to filter on that type .然后您可以覆盖每个子类的save方法以设置正确的type ,并覆盖每个子类的默认查询管理器来过滤该type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM