I created a amount field in models.py,
I run python manage.py makemigrations and python manage.py migrate
It gave me error ValueError: Field 'amount' expected a number but got ''.
then I removed this amount field line from my code and again did makemigrations and migrate command. now again it it showing same error. when I open Django admin page and select my model name which is Orderss . It gives me error that there is no filed name amount
class Orders(models.Model):
order_id = models.AutoField(primary_key = True)
items_json = models.CharField(max_length=5000)
name = models.CharField(max_length=20)
# amount = models.IntegerField(default=0)
email = models.CharField(max_length=20)
address = models.CharField(max_length=50)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
zip_code = models.IntegerField(max_length=6)
phone = models.IntegerField(max_length=12, default="")
def __str__(self):
return self.name
Delete your migrations and delete you db.sqlite3
and then
python3 manage.py makemigrations
python3 manage.py migrate
hope it work
When you did the migration first time, you’ve created the table in the database with ‘amount’ column. The second migration did’t remove this column. You can go to your database shell and remove the column there. It depends on the type of database you use, but you you might try to do it this way:
python manage.py dbshell
mysql> | psql> ALTER TABLE <table_name> DROP column <COLUMN_NAME>;
Then exit the shell and sync
python manage.py syncdb
1.In the Migration folder delete all files except __init__.py and then run
python manage.py makemigrations and
python manage.py migrate
I am using Django ; and when I change a model , getting an error everytime .
I am changing only one field in model, and getting stupidly a lot of errors EVERYTIME.
django.db.utils.OperationalError: no such table:
or
django.db.migrations.exceptions.InconsistentMigrationHistory:
or
OperationalError no such column: table.colunm
or
django.db.utils.OperationalError: "Table already exists"
and bla bla bla..
I got maybe all error types in Django , and now it is bothering me really.
I am trying all solutions everytime :
Delete migrations
find . -path "/migrations/.py" -not -name "init.py" -delete
find . -path "/migrations/.pyc" -delete
Clear the migration history for each app
Remove the actual migration files.
Create the initial migrations
Fake the initial migration
python manage.py migrate --fake
python manage.py migrate --fake-initial
python manage.py migrate --run-syncdb
Drop database
Every solutions what i can find.
Stupidly trying all the solutions , and; at the last , yes i can find solutions BUT , I really really bored now from this stupidly errors.
Is there any way to get rid of migration errors in Django ?
Only I need the answer for this ; 'When I change a model field only, why am I getting these all madly errors, EVERYTIME ??!!!?'
For example :
this is my model :
from django.db import models
from django.conf import settings
from etahfiz.sabitler import DERS_SEVIYESI
# Create your models here.
class Student(models.Model):
systemId = models.CharField(max_length=15, unique=True )
adSoyad = models.CharField(max_length=20, blank=True)
dersSeviyesi = models.CharField(max_length=15,choices=DERS_SEVIYESI )
def __str__(self):
return str(self.systemId)
class Teacher(models.Model):
systemId = models.CharField(max_length=15 , unique=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
adSoyad = models.CharField(max_length=20, blank=True)
def __str__(self):
return str(self.systemId)
class StuTeach(models.Model):
student = models.ForeignKey(Talebe)
teacher = models.ForeignKey(Hoca)
tarihBas = models.DateField()
tarihBit = models.DateField(blank=True, null=True)
This was working perfectly , BUT ; I wanted to add only one field to Teacher Model :
dersSeviyesi = models.CharField(max_length=15,choices=DERS_SEVIYESI )
Teacher model is like this now :
class Teacher(models.Model):
systemId = models.CharField(max_length=15 , unique=True)
user = models.OneToOneField(settings.AUTH_USER_MODEL)
adSoyad = models.CharField(max_length=20, blank=True)
dersSeviyesi = models.CharField(max_length=15,choices=DERS_SEVIYESI )
def __str__(self):
return str(self.systemId)
Aannd when I try to migrate :
python manage.py makemigrations sinif
python manage.py migrate
error error error
django.db.utils.OperationalError: "Table already exists"
Or sth like that..
Everytime that change only one field, getting all errors of Django...
How can I get rid of this type errors ??
Thank you.
Go to your database and find migrations table and also delete on entries. Then run migrations again. At this time you may face ContentType already exists. THen delete content_type table. Or, the easiest solution is to delete the database and create again, but if you have important data, all data will be lost.
So I changed the names and added a column to a model in django.
Before:
class MyApp(models.Model):
id = models.AutoField(primary_key=True)
aaa = models.CharField(max_length=100)
bbb = models.CharField(max_length=100)
After:
class MyApp(models.Model):
id = models.AutoField(primary_key=True)
first = models.CharField(max_length=100)
second = models.CharField(max_length=100)
third = models.CharField(max_length=100)
I made these changes in the MyApp's view, model, and serializer, however when I try to access my new API endpoint, it fails because the database doesn't contain the new column names. How can I update the database to reflect my new model? (I don't care about any of the data for this model, so I can wipe it). No idea how to do this
Make sure you run the commands
python manage.py makemigrations appname
python manage.py migrate appname
If you get table already exists run command
python manage.py migrate --fake appname
This solved the problem when I had it.
https://docs.djangoproject.com/en/1.11/topics/migrations/#initial-migrations
I'm working with a project with docker-compose, where I have a postgre container.
When I run:
docker-compose -f dev.yml run django python manage.py migrate
I get the error:
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "scrapy_scrapy"
That is happening before I made some changes to my models.py file. But now the file is correct and should be working. This is the content of the models.py file:
from django.db import models
import django
# Create your models here.
class Scrapy(models.Model):
user = models.CharField(max_length=50,blank=True)
password = models.CharField(max_length=50,blank=True)
projecte = models.CharField(max_length=100)
estat_last_check = models.CharField(max_length=700, default="", blank=True)
date = models.DateTimeField(default=django.utils.timezone.now, blank=True)
app_label = ''
def __str__(self): # __unicode__ on Python 2
return self.projecte + " - " + self.user
class Meta:
app_label = 'scrapy'
As you can see, no id filed is defined anymore, so, why is complaining about that field?
I've done my research and tried some possible solutions, but no luck. I've already tried deleting the full Docker container and creating it again, or trying to delete the database.
Any ideas?
I'm trying to modify a M2M field to a ForeignKey field. The command validate shows me no issues and when I run syncdb :
ValueError: Cannot alter field xxx into yyy they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
So I can't make the migration.
class InstituteStaff(Person):
user = models.OneToOneField(User, blank=True, null=True)
investigation_area = models.ManyToManyField(InvestigationArea, blank=True,)
investigation_group = models.ManyToManyField(InvestigationGroup, blank=True)
council_group = models.ForeignKey(CouncilGroup, null=True, blank=True)
#profiles = models.ManyToManyField(Profiles, null = True, blank = True)
profiles = models.ForeignKey(Profiles, null = True, blank = True)
Any suggestions?
I stumbled upon this and although I didn't care about my data much, I still didn't want to delete the whole DB. So I opened the migration file and changed the AlterField() command to a RemoveField() and an AddField() command that worked well. I lost my data on the specific field, but nothing else.
I.e.
migrations.AlterField(
model_name='player',
name='teams',
field=models.ManyToManyField(related_name='players', through='players.TeamPlayer', to='players.Team'),
),
to
migrations.RemoveField(
model_name='player',
name='teams',
),
migrations.AddField(
model_name='player',
name='teams',
field=models.ManyToManyField(related_name='players', through='players.TeamPlayer', to='players.Team'),
),
NO DATA LOSS EXAMPLE
I would say: If machine cannot do something for us, then let's help it!
Because the problem that OP put here can have multiple mutations, I will try to explain how to struggle with that kind of problem in a simple way.
Let's assume we have a model (in the app called users) like this:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person)
def __str__(self):
return self.name
but after some while we need to add a date of a member join. So we want this:
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership') # <-- through model
def __str__(self):
return self.name
# and through Model itself
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
Now, normally you will hit the same problem as OP wrote. To solve it, follow these steps:
start from this point:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person)
def __str__(self):
return self.name
create through model and run python manage.py makemigrations (but don't put through property in the Group.members field yet):
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person) # <-- no through property yet!
def __str__(self):
return self.name
class Membership(models.Model): # <--- through model
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
create an empty migration using python manage.py makemigrations users --empty command and create conversion script in python (more about the python migrations here) which creates new relations (Membership) for an old field (Group.members). It could look like this:
# Generated by Django A.B on YYYY-MM-DD HH:MM
import datetime
from django.db import migrations
def create_through_relations(apps, schema_editor):
Group = apps.get_model('users', 'Group')
Membership = apps.get_model('users', 'Membership')
for group in Group.objects.all():
for member in group.members.all():
Membership(
person=member,
group=group,
date_joined=datetime.date.today()
).save()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0005_create_models'),
]
operations = [
migrations.RunPython(create_through_relations, reverse_code=migrations.RunPython.noop),
]
remove members field in the Group model and run python manage.py makemigrations, so our Group will look like this:
class Group(models.Model):
name = models.CharField(max_length=128)
add members field the the Group model, but now with through property and run python manage.py makemigrations:
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
and that's it!
Now you need to change creation of members in a new way in your code - by through model. More about here.
You can also optionally tidy it up, by squashing these migrations.
Potential workarounds:
Create a new field with the ForeignKey relationship called profiles1 and DO NOT modify profiles. Make and run the migration. You might need a related_name parameter to prevent conflicts. Do a subsequent migration that drops the original field. Then do another migration that renames profiles1 back to profiles. Obviously, you won't have data in the new ForeignKey field.
Write a custom migration: https://docs.djangoproject.com/en/1.7/ref/migration-operations/
You might want to use makemigration and migration rather than syncdb.
Does your InstituteStaff have data that you want to retain?
If you're still developing the application, and don't need to preserve your existing data, you can get around this issue by doing the following:
Delete and re-create the db.
go to your project/app/migrations folder
Delete everything in that folder with the exception of the init.py file. Make sure you also delete the pycache dir.
Run syncdb, makemigrations, and migrate.
Another approach that worked for me:
Delete the existing M2M field and run migrations.
Add the FK field and run migrations again.
FK field added in this case has no relation to the previously used M2M field and hence should not create any problems.
This link helps you resolve all problems related to this
The one which worked for me is python3 backend/manage.py migrate --fake "app_name"
I literally had the same error for days and i had tried everything i saw here but still didn'y work.
This is what worked for me:
I deleted all the files in migrations folder exceps init.py
I also deleted my database in my case it was the preinstalled db.sqlite3
After this, i wrote my models from the scratch, although i didn't change anything but i did write it again.
Apply migrations then on the models and this time it worked and no errors.
This worked for Me as well
Delete last migrations
run command python manage.py migrate --fake <application name>
run command 'python manage.py makemigrations '
run command 'python manage.py migrate'
Hope this will solve your problem with deleting database/migrations
First delete the migrations in your app (the folders/ files under 'migrations'
folder)
Showing the 'migrations' folder
Then delete the 'db.sqlite3' file
Showing the 'db.sqlite3' file
And run python manage.py makemigrations name_of_app
Finally run python manage.py migrate
I had the same problem and found this How to Migrate a ‘through’ to a many to many relation in Django article which is really really helped me to solve this problem. Please have a look. I'll summarize his answer here,
There is three model and one(CollectionProduct) is going to connect as many-to-many relationship.
This is the final output,
class Product(models.Model):
pass
class Collection(models.Model):
products = models.ManyToManyField(
Product,
blank=True,
related_name="collections",
through="CollectionProduct",
through_fields=["collection", "product"],
)
class CollectionProduct(models.Model):
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
class Meta:
db_table = "product_collection_products"
and here is the solution,
The solution
Take your app label (the package name, e.g. ‘product’) and your M2M field name, and combine them together with and underscore:
APPLABEL + _ + M2M TABLE NAME + _ + M2M FIELD NAME
For example in our case, it’s this:
product_collection_products
This is your M2M’s through database table name. Now you need to edit your M2M’s through model to this:
Also found another solution in In Django you cannot add or remove through= on M2M fields article which is going to edit migration files. I didn't try this, but have a look if you don't have any other solution.
this happens when adding 'through' attribute to an existing M2M field:
as M2M fields are by default handled by model they are defined in (if through is set).
although when through is set to new model the M2M field is handled by that new model, hence the error in alter
solutions:-
you can reset db or
remove those m2m fields and run migration as explained above then create them again
*IF YOU ARE IN THE INITIAL STAGES OF DEVELOPMENT AND CAN AFFORD TO LOOSE DATA :)
delete all the migration files except init.py
then apply the migrations.
python manage.py makemigrations
python manage.py migrate
this will create new tables.