NOT NULL constraint failed when running `migrate` - django

I changed my models.py file and when running migrate I get this error. The property is a OneToOneField(). I have tried adding null=True but that doesn't seem to fix it. It is also weird that even when I comment out the property and run makemigrations followed by migrate, I still get that exact same error. Is there a way to fix this? My model looks like this:
class Estimator(Employee):
avg_estimate = models.IntegerField()
class Job(models.Model):
created = models.DateTimeField(auto_now_add=True)
estimator = models.OneToOneField(Estimator, null=True)
address = models.CharField(max_length=100)
completed = models.BooleanField(default=False)

My guess is that you have created a migration without null=True, that won't migrate, then you created a second migration with null=True.
Running "migrate" will run both migrations in order, so the first one will fail again.
Assuming this is the case, then
1: delete the two most recent files in your migrations folder. (Open them first to confirm that they are creating the migrations as I described before deleting them).
2: run makemigrations again, with null=True in your models.py
This should create the equivalent of the second migration file, without the failing intermediate migration.

Related

Django - relation "app_name_modelname" does not exist

I've deployed my application to DigitalOcean. Everything works fine except this situation. I've added new GeneralComplaintDocument model, made migration locally, pulled from Github last version of project on DigitalOcean's server, deleted all migration files, migrated again, but still getting this error:
relation "documents_app_generalcomplaintdocument" does not exist
LINE 1: INSERT INTO "documents_app_generalcomplaintdocument"
models.py:
class Document(models.Model):
created_date = models.DateTimeField(default=timezone.now)
added_by = CurrentUserField()
class GeneralComplaintDocument(Document):
complaint_reason = models.CharField(max_length=500)
result = models.CharField(max_length=500)
def __str__(self):
return self.complaint_reason
P.S: everything works fine on local server.
I would suggest for do something like this:
first delete all migrations files in your app(documents_app)and next execute the below SQL query in your Database. Here we assume your app_name is documents_app.
delete FROM "django_migrations" WHERE "app" = 'documents_app';
then migrate ,
python manage.py makemigrations documents_app
python manage.py migrate documents_app

How to add new field to existing django model postgres

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

Add more fields in the model and get the error "column ... does not exist"

I have a model like this :
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.CharField(max_length=100)
city= models.CharField(max_length=100)
, after a while, I add 2 more fields to this:
zip_code = models.CharField(max_length=20, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
, then I do the routine
python manage.py makemigrations
python manage.py migrate
But when I go to website/admin and check that model in Django Administration, I got the error "column user_profile.zip_code does not exist"
I search for the solution and some threads suggested to use South but then I learned that from django >= 1.7 we don't need to use South for migrations.
Please show me where I am wrong.
Thank you!
Check that you use the same settings when running migrate and the server.
If you are using django debug toolbar in your installed apps. Make sure to comment that, that gives the issue. If not, you can also check if your models are used by forms in another app or not. If they are its better to move the logic into views.
I commented out the debug toolbar, but that did not solve the problem.
I was adding a field to the user model. I have a utility that returns the default user. When I tried to migrate (adding the new field), that utility was getting called and was causing the error.
The solution that worked for me: in the utility that returns the default user, temporarily commenting out calls to the user table, and returning None for the default user. Migrate then ran successfully. Then of course I restored the code in the utility.
I found out that my utility was causing the problem by finding a line from my code in long list of exceptions displayed in the terminal.

Migrations in Django 1.7

I am currently involved in a project where I am using Django 1.7 development version.I want to propogate changes that I make in my models (adding a field, deleting a model, etc.) into the database schema using "makemigrations" and "migrate" commmands.I added a "age" field to one of the models in my application.
country = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=100, blank=True)
postal_code = models.IntegerField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
phone_no = models.CharField(max_length=25, blank=True)
skype_name = models.CharField('Skype Username',max_length=50, blank=True)
age=models.IntegerField(max_length=25,blank=True)
When I use "makemigrations" command ,the output is like---"No changes detected".I guess that "makemigrations" is not able to figure out the changes made to the schema.Any suggestions how can I make it work??
If you are adding initial migrations to an app, you must include the app name when using the makemigrations command.
python manage.py makemigrations your_app_label
If it is the first time you are migrating that app you have to use:
manage.py makemigrations myappname
Once you do that you can do:
manage.py migrate
If you had your app in database, modified its model and its not updating the changes on makemigrations you probably havent migrated it yet.
Change your model back to its original form, run the first command (with the app name) and migrate...it will fake it. Once you do that put back the changes on your model, run makemigrations and migrate again and it should work.
I have sometimes the same problem.
I manage to populate the change in the database by following :
rm -rf your_app/migrations/*
python manage.py migrate
if it doesn't work, consider a manual drop table before, if you don't have data in it.
it worked for me with django 1.7c1

Allow null in foreign key to user. Django

I have this model
class Vacancy(models.Model):
user = models.ForeignKey(User, null=True, blank=True, default = None)
name = models.CharField(max_length=64)
When in admin i try to creat a vacancy without a user. And it throws an error " club_vacancy.user_id may not be NULL".
Am i doing something wrong?
club_vacancy.user_id may not be NULL
Looks very much like an error from your database, rather than from Django.
It seems most likely that you added null=True after running manage.py syncdb. You'll need to modify your database schema to allow null values in that column.
Aside from South, another option is to use django evolution for schema changes.
http://code.google.com/p/django-evolution/
Install it before making db changes. Then run
python manage.py evolve --hint --execute
Make sure that if you add a new field, you allow nulls (null=True) or else evolve will give you an error message.
you need to reset you database table (since just syncdb does not update fields that are alredy created with null=False)
./manage.py reset your_app
OR if there is some data that you do not want to loose use SQL commands to remove NOT NULL flag