Whenever I add a new column to my model I get:
django.db.utils.OperationalError: no such column: companies_company.[name of added column]
For example, I just added "employee_count" and whenever I run
python manage.py makemigrations
I get:
django.db.utils.OperationalError: no such column: companies_companyadmin.employee_count
My model.py looks like this:
from django.db import models
import csv
class Company(models.Model):
name = models.CharField(max_length=70, blank=True)
description = models.CharField(max_length=1200, blank=True)
employee_count = models.IntegerField(blank=True)
class CompanyAdmin(models.Model):
name = models.CharField(max_length=70, blank=True)
description = models.CharField(max_length=1200, blank=True)
employee_count = models.(blank=True)
with open("organizationTest.txt","rU") as f:
reader = csv.reader(f)
for row in reader:
_, created = Company.objects.get_or_create(
name=row[3].decode('latin-1').encode('utf8'),
description=row[15].decode('latin-1').encode('utf8'),
)
The CSV part is simply to populate my DB (I should probably do it somewhere else).
And my admin.py:
from django.contrib import admin
from .models import Company
class CompanyAdmin(admin.ModelAdmin):
pass
admin.site.register(Company, CompanyAdmin)
This also happens when I try to run the server or "syncdb".
If anyone knows why this is happening and how I could fix this I would love to know! Thanks in advance! I'm happy to answer any questions you may have.
In my case I had an initial value in some Querysets of an updated model. When I removed these initial statements, makemigrations had worked.
Appears my original answer wasn't clear enough.
Company.objects.get_or_create(
name=row[3].decode('latin-1').encode('utf8'),
description=row[15].decode('latin-1').encode('utf8'),
)
This block is out of a class so it runs when the server is started or basically everytime manage.py is run. Company.objects.get_or_create(...) is trying to run, on the updated database model that can't be created yet. To make the migrations you have to comment this line out, then make the migrations, then it will work.
Related
I'm using Django 3.0.5 and I am trying to create a new column in a table.
The table looks like this:
class VacationModel(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
emp_id = models.IntegerField()
email = models.EmailField()
from_date = models.DateField()
to_date = models.DateField()
reason = models.TextField()
time_sent = models.DateTimeField("date sent")
req_approved = models.BooleanField(default=False, null=True)
req_denied = models.BooleanField(default=False, null=True)
# daysoff_given = models.IntegerField()
def __str__(self):
return self.emp_id
The new column would be daysoff_given. I tried adding this column and after running python manage.py makemigrations I got an error saying django.db.utils.OperationalError: no such column
I tried following some other answers and I deleted the migrations made inside the migrations folder, without deleting the __init__.py file. After running makemigrations again the same error occured and then I deleted the whole model and made a new model.
I think my database is broken, but is there an actual way to avoid this, since it has already happened two times.
Whenever I try to add a new column, it always throws that error and I cannot continue. How can I fix this?
I think the problem is that you created migrations but didn't apply them. Make sure you run both of the following commands after adding the column in the Model.
python manage.py makemigrations
python manage.py migrate
It it doesn't work, please edit your question and add the full trackback error to help us know what is the causing the error.
Background: I started a project with a custom User model. However, noob that I am, I was unaware of the AbstractBaseUser class. So I just wrote my own. The app has been deployed to prod and working fine. But now I want to switch to using AbstractBaseUser so I can take advantage of some of the built-in Django utilities (like the pre-made password resetting process). I had done this with a different app and it worked fine. But that one wasn't in prod while I made the change. Because this one is, I needed to keep the old user table while I made the changes with a copy of it. So my first step was to add db_table = test_users to my old user model, so as to keep the prod app running with an unchanged table. I ran the migration, and two unexpected things happened (I'm a noob, and that's why they were unexpected):
The old user table was renamed. I thought a new table would be created. No problem, I quickly copied the new table and named the copy with the old table's name so the prod app could still find its users
A column last_login was added. Why??
Here's my model, with the added db_table
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
client_id = models.IntegerField(blank=True, null=True)
is_admin = models.BooleanField(default=False)
is_super = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
class Meta:
db_table = "test_users"
The big problem with this is that when I change to AbstractBaseUser and run the migration, I get an error. Looking at the migration file I see that this change creates a migration that all it tries to do is to add last_login to the table. So, of course, the error I get is "Duplicate column name 'last_login'"
So, my question is two-fold:
Why was that column added in the first migration?
If I just run migrate --fake and keep going, will it have unintended consequences? I thought this could be a good solution, given that the migration file shows nothing else is being done, and if the field already exists, then no harm done?
Maybe because you've changed the parent class django automatically change all the migrations that connected to your user class
Ok So I have some migration issue in django 1.8 and I need to work around by manually dropping my DB table every time.
My problem is following - every time after I change my table by adding new fields and running
python manage.py makemigrations
python manage.py migrate
it says no changes to apply. (migrate folder is empty)
(It is not picking up changes I made in model file )
At the end table stays with old structure and it gives me errors when I test.
If I drop table in DB directly and start again it works but it is annoying since I have to recreate a test data every time.
Is it a bug in migration or just me ?
For example this is my table from models file but it happened before with other tables.
#with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
product= models.ForeignKey(Product, on_delete=models.PROTECT)
material = models.OneToOneField(Material, related_name = 'material')
creation_time = models.DateTimeField(auto_now_add=True)
materialuom = models.CharField(max_length=1,
choices=UOM_CHOICES)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
waste = models.DecimalField(null=True, blank=True,max_digits=19, decimal_places=10)
def __unicode__(self):
return u'%s %s' % ( self.id, self.name)
Ok so I got my work around thanks to comment from #ahmed.
Every time when doing python manage.py makemigrations appname it is mandatory to type the appname .Without the appname functionality is not always working.
However I believe there is still problem in django1.8 migrate process.
I am stuck with an Error with models.DateField()
First, I did this.
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField()
Then, I got,
$ python manage.py makemigrations
You are trying to add a non-nullable field 'birthdate' to user_profile 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
So, I did,
models.py
from datetime import date, datetime
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
birthdate = models.DateField(default=date.today)
Then,
$ python manage.py migrate
django.core.exceptions.ValidationError: ["'' は無効な日付形式です。YYYY-MM-DD形式にしなければなりません。"]
The error means, like "'' is invalid for formate of date. You should change to YYYY-MM-DD".
How should I change this code?
Thank you.
/// additional ///
If I can, I don't want to INSERT date INTO birthdate field. But it seems I have to. Can I let it blank?
birthdate = models.DateField(null=True, blank=False)
didn't work.
Python 3.5.1
Django 1.9.1
Sounds like your migration files are messed up. When you do a migration, django would create a migration file that records what you did. So in short, you changed your model code many times, but you never changed your migration file, or you are creating duplicate migration files.
The following should be what you want,
birthdate = models.DateField(null=True, blank=True)
But as you noticed, cleaning up all migration files that related to this change and create a new one should solve the problem.
What you have tried should work:
birthdate = models.DateField(null=True, blank=False)
This allows the database to accept null values (which it does during the migration) and blank means that django will not accept empty values from forms.
Make sure to delete migrations that have been made but not applied. Also try deleting all .pyc's in your project.
Try this,
birthdate = models.DateField(null=True, blank=False)
i am failing to migrate using south. the problem is this:
i created a model, then i did schemamigration app --auto, then migrate app, it was fine. then later on, i added another field to this model and then did again those two commands, but now it is saying, column 'None' doesnot exist. i think, it was because i had a foreignkey field and that didnot have default value, i added some empty string default value, then did the commands again, it said the same error, now i deleted the model and did schemamigration and migrate app, but it still keeps giving this error.
this is my model:
class User(models.Model):
registerdate = models.CharField(max_length=400,default='')
vorname = models.CharField(max_length=100,default='')
nachname = models.CharField(max_length=100,default='')
email = models.EmailField(max_length=100,default='')
strasse = models.CharField(max_length=100,default='')
hausnr = models.CharField(max_length=100,default='')
stadt = models.CharField(max_length=100,default='')
land = models.CharField(max_length=100,default='')
##for confirm mails - the hash
unique = models.CharField(max_length=400,default='')
kennwort = models.CharField(max_length=200,default='')
username = models.CharField(max_length=200,default='')
locations = models.CharField(max_length=10, default='')
can someone please help me?
thanks a lot
field_name = models.CharField(max_length=400, blank=True)
You will have to edit your migration file, or regenerate it with a valid default. Your assumption of the invalid default is correct.