How to add base class to existing django model

0

I have class A with instances in production, and I want to add a base class B, currently:

class A:
    name = models.TextField(max_length=1000)
    phone = models.TextField(max_length=30)

and what I need is:

class B:
    name = models.TextField(max_length=1000)

class A(B):
    phone = models.TextField(max_length=30)

The problem is that when doing this, when I do the makemigrations, it asks me for a value for b_ptr (which is not clear to me, and if I put null or any number does not work)

"You are trying to add to a non-nullable field b_ptr 'to to without a default; we can not do that (the database needs something to populate existing rows) "

I appreciate if you can give me a hand.

    
asked by Jonathan 19.10.2018 в 19:01
source

2 answers

0

What you want to do is called inheritance, what happens is that when you make class A(B) two tables A and B are created and to relate A with B in A you create a FK nametable_ptr with B, options to correct your problem:

  • Delete all the records you have in A, because if you have records you can not create an FK field with null because it is required
  • Before doing the inheritance create table B and add a record for example with id = 1, then do the inheritance and when it asks for a default value you say that 1, is the id of the record that you added in the Table B
  • If none of the previous ones works for you, you will have to delete table A and recreate it, so that you have problems with the migration files, do not delete the table directly from the database, but comment on the model A run the migrations so that it eliminates the table, then descomenta returns to run the migrations so that it creates the table with the inheritance.
  • answered by 19.10.2018 / 21:17
    source
    0

    The simplest way is to delete the migration files that are in the migrations folder. Remove only those that are numbered. In this way, the migration is carried out as if it were the first time. Keep in mind that this can be done in case you are not interested in the accumulated data Once the migration files are deleted, you return to execute makemigrations [app]

        
    answered by 26.10.2018 в 16:28