0

Let's suppose I have the following model:

class Test(models.Model):
   field_one = models.CharField(max_length=80)

Now, we have created 2-3 Model objects with field_one field.

p1 = Test(field_one="Object1")
p1.save()
p2 = Test(field_one="Object2")
p2.save()

Later, I realised that I need to add another field field_two to my Test model.

class Test(models.Model):
   field_one = models.CharField(max_length=80)
   field_two = models.IntegerField(default=3)
  • Now, Doing makemigrations & migrate and running server.

which will prompt the following error

django.db.utils.ProgrammingError: column mainapp_test.field_two does not exist
  • I understand that this error occurs due to my 2 existing objects in PostGresDB doesn't have field_two column.

Is there any effective way to add field_two column to my existing objects with some default value? or How to solve this problem?

Django Version: 2.0 Django ORM DB: PostGresql

1
  • can you show the relevant part migration file generated by makemigrations? Commented Oct 16, 2019 at 18:07

1 Answer 1

1

When you add a field to an existing model, you must either provide a default value in the code, or set it to null/blank = True, or provide a one-off default while migrating.

Since you are providing a default in the code, the migration should run without issues. At least from experience, I've added several BooleanFields with default=False to my existing model with thousands of entries, and I never got a ProgrammingError.

Have you tried shutting down the Postgres backend before running makemigrations and migrate? I would think Django would do this but that's the only thing I can think of. Also, obviously, shut down the Django server if it's still running.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, but i did messed but with my migrations , had to delete a column of django_migrations to get it fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.