django.db.utils.IntegrityError: The row in table 'main_tutorial' with primary key '1' has an invalid foreign key: main_tutorial.tutorial_series_id contains a value 'tutorial_series_id' that does not have a corresponding value in main_tutorialseries.id.
The above error shows up and cant migrate
These are my models:
from django.db import models
from datetime import datetime
#Create your models here.
class TutorialCategory(models.Model):
tutorial_category = models.CharField(max_length=200)
category_summary = models.CharField(max_length=200)
category_slug = models.CharField(max_length=200, default=1)
class Meta:
#Gives the proper plural name for admin
verbose_name_plural = "Categories"
def __str__(self):
return self.tutorial_category
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory, default=1,verbose_name="Category", on_delete=models.SET_DEFAULT)
series_summary = models.CharField(max_length=200)
class Meta:
#Otherwise we get "Tutorial Serie*ss* in admin"
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField("date published", default = datetime.now())
tutorial_series = models.ForeignKey(TutorialSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT)
tutorial_slug = models.CharField(max_length=200,default=1)
def __str__(self):
return self.tutorial_title
I faced the same problem just I am also working with the same. All you got to do is to
just delete "migrations" folder from the "main()" and also the db.sqlite file too.
The error is probably occurring because we have Tutorial already in db
which is not linked to TutorialSeries so.., to make it linked to the
db, make the changes above and then again perform commands.
What I got was:
python manage.py makemigrations
Output:
No changes detected
Next one
python manage.py migrate
Output:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK
Make sure while performing these commands you have linked Tutorial
with TutorialSeries. And guys making things done this way makes you earlier data lost from the database. Be careful about that.
Have a Nice day & happy coding.😁
You can simply delete all the objects in the main_tutorial table from django shell:
goto command prompt
python manage.py shell
from main.models import Tutorial
Tutorial.objects.all().delete()
(main being the app name here)
This will delete all the objects in the Tutorial table and then makemigrations and migrate and it should work just fine.
In your Tutorial model, you are using a default value for the foreign key field ** tutorial_series **. This causes the migration to check if a record in TutorialSeries exists with id=1 but there is no such data present, so the error is occuring.
To avoid the error while migrating, remove the on_delete=models.SET_DEFAULT and default=1 from our fields to make your models as:
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory,verbose_name="Category")
series_summary = models.CharField(max_length=200)
class Meta:
#Otherwise we get "Tutorial Serie*ss* in admin"
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField("date published", default = datetime.now())
tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", blank=True, null=True) #<--changes
tutorial_slug = models.CharField(max_length=200,default=1)
def __str__(self):
return self.tutorial_title
After this, migrate your models. Then add data to TutorialCategory and TutorialSeries with id=1.
Then revert your models to your initial setup (keeping default=1 and on_delete=models.SET_DEFAULT). Then again run makemigrations and migrate your models. After this, your problem might be solved.
Try to delete all the migration files exept __init__.py and also delete db.sqlite3. After that run makemigrations and migrate again
Try using on_delete = models.CASCADE without a default parameter.
I was dealing with the same issue. I deleted everything inside migrations except _init__.py and also the sqlite database. Then ran- py -3.7 manage.py makemigrations, then after that, py -3.7 manage.py migrate. Then it worked!
I had this issue a while ago.
The above answer maybe correct but it didnt work for me because
-im using postgres, i cant just delete the database
-migration files were commited in git.
My situation was, I have 004 migration file but i cant run it because of IntegrityError.
I checked the file, and i saw it was in operation list.
The first item of list is migrations.CreateModel and the second was migrations.AddField
here are my steps:
I commented the second item in list, only the CreateModel is remaining.
then run the migrate
open the django admin page and add it manually the missing id
you can add it also in database editor or update statement.
uncomment the AddField section and rerun the migrate.
from django.db import models
from datetime import datetime
class TutorialCategory(models.Model):
tutorial_category = models.CharField(max_length=200)
category_summary = models.CharField(max_length=200)
category_slug = models.CharField(max_length=200)
class Meta:
verbose_name_plural = "Categories"
def __str__(self):
return self.tutorial_category
class TutorialSeries(models.Model):
tutorial_series = models.CharField(max_length=200)
tutorial_category = models.ForeignKey(TutorialCategory, verbose_name="Category", on_delete=models.CASCADE, blank=True, null=True)
series_summary = models.CharField(max_length=200)
class Meta:
verbose_name_plural = "Series"
def __str__(self):
return self.tutorial_series
class Tutorial(models.Model):
tutorial_title = models.CharField(max_length=200)
tutorial_content = models.TextField()
tutorial_published = models.DateTimeField('date published', default=datetime.now)
tutorial_series = models.ForeignKey(TutorialSeries, verbose_name="Series", on_delete=models.CASCADE, blank=True, null=True)
tutorial_slug = models.CharField(max_length=200, default=1)
def __str__(self):
return self.tutorial_title
Try this, it's work for me.
But remember, you will need to type this code before you have done "python3 manage.py makemigrations" and "python3 manage.py migrate"
The following answer was been posted on the Django tutorial comments of sentdex by nice folks namely: "Kevin di" and "JOSEPH Blessingh". The recommendation helped me and worked like charm:
There is a file " db.sqlite3 " in your working directory, you can open it with any database management tools that supports SQLite type.
following the steps:
For example, " DB Browser for SQLite ", you can Google and download it.
Opening the " db.sqlite3 " file, navigate to the Tables.
Find the main_tutorial table. (Maybe you used another table name in the previous lessons, use your table name.)
Delete record from the table: main_tutorial.
Try python manage.py migrate again.
The meaning of Delete Record from the table can be explained as:
- Click main_tutorial
- Then you might see a tab with the name Browse Data
- Click it and you will see your records
- Press Ctrl + Left Mouse button on the number on the left hand side column to select all the rows
- Delete them using right click
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.
I created a CustomUser model, inheriting from AbstractEmailUser.
I wanted to add an avatar field, after finishing it and making migrations but I'm getting the following error:
column account_customuser.avatar does not exist
LINE 1: ...user"."name", "account_customuser"."valid_email", "account_c...
models.py looks like this now
class CustomUser(AbstractEmailUser):
nickname = models.CharField('nickname', max_length=100, unique=True)
name = models.CharField(max_length=200, blank=True, null=True, default=None)
valid_email = models.BooleanField('valid email', default=False, blank=True)
avatar = models.ImageField(upload_to='profile/photo', blank=True, null=True, default=None)
What can I do to correctly add the avatar field?
As stated here: Django Programming error column does not exist even after running migrations
Something may have gone wrong in your migration process.
Go to your database and find a table named django_migrations where
all the migrations are listed.
Find the row with the migration in which you added the avatar column to your model and delete it from the database (only the row).
Migrate again: ./manage.py migrate
Another possibility is that you are using Django Toolbar like what happened here: Django Migration Error: Column does not exist, in which case you need to comment the toolbar in your installed apps and rerun migrations.
Did you apply a new migration with these changes?
You can check this using showmigrations or use makemigrations to create a migration and migrate to apply it.
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.
Consider a clean django 1.7.7 project with one app called testrunner.
The models look like this:
class Contact(AbstractBaseUser, PermissionsMixin, models.Model):
relation = models.ForeignKey('tests.Relation', related_name='contacts')
username = models.CharField(max_length=200, unique=True)
first_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30, null=True, blank=True)
email = models.EmailField(null=True, blank=True, unique=True)
is_staff = models.BooleanField('staff status', default=False,
help_text='Designates whether the user can log into this admin site.')
is_active = models.BooleanField('active', default=True,
help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')
USERNAME_FIELD = 'username'
def get_full_name(self):
pass
def get_short_name(self):
pass
def get_name(self):
pass
class Relation(models.Model):
name = models.CharField(max_length=200, unique=True)
created_by = models.ForeignKey('tests.Contact', null=True, related_name='created_%(class)s')
modified_by = models.ForeignKey('tests.Contact', null=True, related_name='modified_%(class)s')
def natural_key(self):
return (self.name,)
In the settings.py I've set 'tests.Contact' to by the AUTH_USER_MODEL.
This setup is a clean test to replicate the error I get within a larger environment. The problem is that I cannot run the django tests without it failing on the creation of the test database:
manage.py test
Testing started at 14:39 ...
Creating test database for alias 'default'...
CommandError: Can't resolve dependencies for tests.Contact, admin.LogEntry, tests.Relation in serialized app list.
Process finished with exit code 1
Empty test suite.
When I remove the def natural_key(self) from the Relation model everything works fine.
We would like to use the natural_key on the Relation model for our fixtures, but are unable to get it to work with django tests.
What am I doing wrong?
A very simple solution, yet took me some time to come up with.
tl;dr
Dynamically import serializers.
Dynamically define natural_keys method & assign to model.
def method_where_serializers_is_being_used():
# import serlializers
from django.core import serializers
# define natural_key method
def natural_key(self):
return some_unique_id
DjangoModel.natural_key = natural_key
It's a kind of a hack, but its working fine
The problem here is a circular dependency involving natural keys that Django fails to handle properly. Since this post was made, the loading of such data was already much improved, but serialization still breaks on a (now pretty obsolete) check for circular dependencies.
This is an open bug and reported here: https://code.djangoproject.com/ticket/31051
I've completely wiped all my database tables in order to add a new field to a model since wiping SQL tables clean is the fastest way to do so without going the 'south' route when the SQL data only contains dummy data for testing purposes.
So here's my Model:
class Student(models.Model):
uid = models.ForeignKey(User)
title = models.CharField(max_length=250, help_text='The student name.')
resume = models.FileField(upload_to=get_upload_resume_name)
location = models.ForeignKey(Location)
country = models.ForeignKey(Country)
prim_interest = models.CharField(max_length=250, help_text='Maximum 250 characters.')
sec_interest = models.CharField(max_length=250, help_text='Maximum 250 characters.')
cellphone = models.IntegerField(default=0)
email_verified = models.BooleanField(default=False)
thumbnail = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.title
and the last field that I've added called 'thumbnail' is not being created by Django when I call syncdb right after deleting all my tables.
My method of completely wiping the tables has always worked no matter what drastic changes are applied to models.py and suddenly this is not the case for this instance. I could show you more code snippets but I have no clue where else in the Django project has a direct effect on generating models.
What could be causing syncdb to be refusing to write this new field 'thumbnail' to the Student table in the DB?
Could be That south is interfering. You habe no migrations waiting. If I remember well syncdb dos not create tables That south is scheduled to create.
Why not make a south migrate after your syncdb?