本文介绍了Django模式继承 - 我可以改变模型类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用多表继承时,Django创建两个表 - 一个用于基类,一个用于派生的表,指向第一个。有没有办法在删除派生的条目时保留基表条目,并为另一个模型创建另一个条目?

When I use multi-table inheritance, Django creates two tables - one for the base class, and one for the derived one, pointing to the first. Is there a way to keep the base table entry while deleting the derived one, and create another entry for another model?

简单说来:我有模型:A, B(衍生自A),C(衍生自A)。我想将类型B的对象转换为类型C.复制不是一个好的解决方案,因为A用作一组项目,所以项目使用ForeignKey指向。

To put it simpler: I have models: A, B(derived from A), C(derived from A). I want to convert an object of type B to type C. Copying is not a good solution because A serves as a set of items, so items point to it with a ForeignKey.

推荐答案

没有内置的方法来做到这一点。如果您需要保留基表中的条目,因为FK指向它,则必须编写一些管理器方法来使用原始SQL来操作B和C表。

There is no built-in way to do this. If you need to preserve the entry in the base table because FKs are pointing to it, you'll have to write some manager methods to manipulate the B and C tables using raw SQL.

如果您使用的RDBMS不支持引用完整性,那么您可能只需复制数据,删除B实例,并使用PK手动设置为B的PK创建C实例。

If you're using an RDBMS that doesn't support referential integrity, you might be able to just copy the data, delete the B instance, and create the C instance with the PK manually set to B's PK.

这篇关于Django模式继承 - 我可以改变模型类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:26