MMakela
MMakela

Reputation: 167

Adding fields to existing model doesn't work in Django

I have already created own model with OneToOneField with User-model. Now, I want to add field to that model, but doing manage.py makemigrations and migrate doesn't see any changes, which I made to my models.py.

models.py:

class UserDetails(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,)
    footsize = models.CharField(max_length=10)
    headsize = models.CharField(max_length=10)

    handsize = models.CharField(max_length=100) #field what I want to add

    def __str__(self):
        return u'%s %s %s' % (self.id, self.footsize, self.headsize)

If I try to add values to handsize with shell, I get an error that the handsize field doesn't exists. What's the problem?

Upvotes: 2

Views: 4013

Answers (2)

MMakela
MMakela

Reputation: 167

I tested to do same thing as in my question with my backup. Terminal show this message, when doing makemigrations:

You are trying to add a non-nullable field 'handsize' to userdetails without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:

I'm sure, that I answered earlier with 1), so that's why field didn't show in the database. So, now I answered 2) and added default value to the field:

    handsize = models.CharField(max_length=10, default='40')

Now migrate works and adds handsize as a new field to database.

Upvotes: 3

Rajesh Yogeshwar
Rajesh Yogeshwar

Reputation: 2179

When you said that you have already created model, I assume that you ran initial migrations. So, when running migrations again after putting in new fields, you can't run blanket migrations. You will have to specify app name after makemigrations. Something like this.

./manage.py makemigrations app_name

and the

./manage.py migrate.

Should work.

Upvotes: -1

Related Questions