0

I have two models:

# 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

In initial migration for app2 django creates OneToOneField with parent_link=True named parentmodel_ptr.

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)
        )
    ]

Trying to migrate, I got an exception

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?

valignatev
  • 6,020
  • 8
  • 37
  • 61

1 Answers1

1

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).

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.

wanaryytel
  • 3,352
  • 2
  • 18
  • 26
  • Actually, you got it right. Spending all night hacking on ModelBase I finally realized that the best way is to create explicit OneToOneField and migrate _ptr to it in data migration e.g. User way from auth package. So I think your answer approves this thought :) Thanks! – valignatev Sep 25 '16 at 22:26
  • can you please suggest an answer here: https://stackoverflow.com/questions/63408566/running-custom-migrations-to-change-database-schema – Mohit Harshan Aug 14 '20 at 13:49