迁移中自动生成的_ptr字段上的AlterField导致FieldError [英] AlterField on auto generated _ptr field in migration causes FieldError
问题描述
我有两个模型:
# app1
class ParentModel(models.Model):
# some fields
现在,在另一个应用程序中,我有子模型:
Now, in another app, I have child model:
# app2
from app1.models import ParentModel
class ChildModel(ParentModel):
# some fields here too
在最初迁移 app2
django使用 parent_link = True
创建名为 parentmodel_ptr
OneToOneField >。
In initial migration for app2
django creates OneToOneField
with parent_link=True
named parentmodel_ptr
.
现在,我想更改此自动生成的字段,例如 IntegerField
,因此我使用此操作:
Now I want to change this auto generated field to let's say IntegerField
, so I create new migration with this operations:
class Migration(migrations.Migration):
dependencies = [
('app2', '0001_initial'),
]
operations = [
migrations.AlterField(
'childmodel',
'parentmodel_ptr',
models.IntegerField(null=True, blank=True)
)
]
尝试迁移时,出现异常
django.core.exceptions.FieldError: Auto-generated field 'parentmodel_ptr' in class 'ChildModel' for parent_link to base class 'ParentModel' clashes with declared field of the same name.
那么是否有可能做到这一点?
So is that even possible to make it somehow?
推荐答案
如果您的代码支持,则可以将父类更改为抽象类,并在子模型中包含所有字段。但是,如果您仍然确实需要单独使用父对象,那么我认为您可以在没有严重黑客入侵的情况下更改Django OneToOne链接(不推荐)。
If your code supports it, you could just change the parent class to an abstract class and have all the fields in the child model. However, if you still do need the parent object separately, then I don't think you can change the Django OneToOne link without some serious hacking (not recommended).
如果您只需要关系而不需要方法等,则可以删除继承并使用自己创建的OneToOneField或IntegerField将ForeignKey保留到另一个对象。您可以使用最终目标来详细说明问题,因此提供实际的解决方案而不是理论会更简单。
If you only need the relation and don't need the methods, etc. then you could remove the inheritance and go with a self-created either OneToOneField or an IntegerField that holds the ForeignKey to that other object. You could elaborate the question with your end goal, so it would be simpler to offer real solutions rather than theories.
这篇关于迁移中自动生成的_ptr字段上的AlterField导致FieldError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!