I am trying create a new model with Django, but I keep running into the error Lookup failed for model referenced by field help.HelpDefinition.org: account.Organization. Organization has been imported. You can see the model below.
models.py
org = models.ForeignKey(Organization, unique=True)
help_type = models.CharField(max_length=255, choices=HELP_CHOICES)
help_content = models.TextField(blank=True)
This model has been successfully migrated previously. I dropped the table via psql in Postgres so that it could be recreated.
It happens when you change the target objects in relationship. Even if they have the same name and fields they are not the same objects. I had the same issue and deleting all previous migrations from migrations folder solved it.
You can also add as a dependency to the migration the last migration from the object's app. That did the trick for me.
class Migration(migrations.Migration):
dependencies = [
(<app>, <last_migration_filename>),
...
My case was: moving away from South I deleted almost all migration files from several apps and applied makemigrations and migrate and later on I found out some forgotten migrations in one app and I tried to do the process (delete/makemigrations) only for this one app. But going back one step and recreating the migrations for ALL the apps fixed the issue for me.
Related
Creating test database, Django is raising this exception
django.core.exceptions.FieldError: Cannot resolve keyword 'xxx' into field. Choices are: ...
The failing migration is a custom one, moving data from (let's say) ModelA to ModelB:
def forwards(apps, schema_editor):
...
prev_list = ModelA.objects.all().values_list('xxx').distinct()
for item in prev_list:
ModelB(xxx=item).save()
My next movement has been checked ModelA which, ok expected, doesn't have a field called XXX
class ModelA(Model):
# no field named xxx
Digging a little bit what happened here:
ModelA used to have a field named xxx
there is a migration trying to create ModelB rows reading from ModelA.xxx
ModelA doesn't have such field since there is a later migration removing that field, so I don't have the field declared in my model.
Why is failing the creation of the test database (from python manage.py test)?
how can I fix this?
You shouldn't import ModelA directly, but import the historical version as below (see documentation on writing migrations here).
ModelA = apps.get_model('myapp', 'ModelA')
According to the docs, you can edit an old migration if you run into this problem:
...historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes.
I'm trying to extend the User model of a django app, but I keep getting the error:
OperationalError at /admin/auth/user/3/
Exception Value: no such column: subjects_subject.user_id
My Code:
#subjects/models.py
from django.contrib.auth.models import User
from django.db import models
class Subject(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=100)
models.signals.post_save
#_admin/admin.py
from django.contrib.auth.models import User, Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from .extended_admin import new_admin
from django.contrib import admin
from subjects.models import Subject
class SubjectInline(admin.StackedInline):
model = Subject
can_delete = False
verbose_name_plural = 'subject'
class UserAdmin(UserAdmin):
inlines = (SubjectInline, )
new_admin.register(User, UserAdmin)
new_admin.register(Group, GroupAdmin)
I have pretty much copied Django's own documentation word for word. Any help would really be appreciated!
EDIT:
I also wanted to say that I have ran syndb and flush
I had the same issue and here are the steps I took to solve it. You did not specify the database you are using but in my case I am using MySQL. From Django docs here https://docs.djangoproject.com/en/1.8/topics/migrations/#mysql it seems sometimes creating the tables fails. I had a table called 'administration' and that kept failing to detect any changes.
Here is what I did:
Remove migration directory from my app. This was so as to create new migration schemas
Rename the directory. I renamed my directory from 'administration' to 'donor'. For some weird reason this seemed to fix the issue. I am not entirely sure why but could be 'administration' is a key word in either MySQL or Django
If both steps do not work, you might have to manually add the changes as directed on the django docs. Even easier, you can drop the existing table if its empty and recreate it. (WARNING! Please only do this if the table is empty otherwise you risk losing all your data)
All in all, there seems to be no outright reason as to why this could be happening at the moment. My trial and error approach seems to have fixed it.
Did you solved this problem?
I had the same issue , after different trying , I solved this. I'm using sqlite3 .
it seems like the when you first migrate , there is something wrong with the database table (I don't know what this problem caused by , so you raise the error : no such column: subjects_subject.user_id)
if you remove the migrations directory , and re-migrate , that will not solve this problem , because Django keeps track of all the applied migrations in django_migrations table.Migration was faked because the table already existed (probably with an outdated schema)SO I delete all the rows in the django_migrations table.
Here is what I did:
1.remove all files in migrations directory in my django app
2.using python manage.py dbshell , then DELETE FROM django_migrations WHERE app='your-app-name or DELETE FROM django_migrations WHERE ID='your-first-migrate
3.then python manage.py makemigrations python manage.py migrate
Successful!
I'm trying to update a field key from the following in the model:
name = models.CharField(max_length=255, unique = True)
to:
name = models.CharField(max_length=255, unique = False)
However I need to update the mysql db without losing any of the current data. How would I go about doing this? I tried $ python manage.py syncdb but it doesn't seem to update the key.
That is because syncdb doesn't do that. It only creates new tables, but doesn't change the existing if your model changes.
On a dev environment, to update your database after changing your model, you can use python manage.py reset appname to empty out your database, and use syncdb again.
Otherwise, you have to use tools such as South. South was made to handle migrations, but also changing the database when the model changes.
There is also django-evolutions that does just what you want, but I still recommend South as its migrations features are almost always going to be of some use.
You could use PHPMyAdmin and remove the unique index from this field.
I have a DateTimeField in one of my Django models.
completed_date = models.DateTimeField('date completed', blank=True, null=True)
I've defined it to allow blank and null values. However, when I try to create an instance of the model, I get the following error:
IntegrityError at
/admin/tasks/project/add/
tasks_project.completed_date may not
be NULL
I'm using Django 1.25 and Python 2.7. Anyone know why this is happening? Is there anything I can do to fix this?
I found a ticket that describes the same problem, but it was closed as fixed 4 years ago, so I assume it must have been integrated into Django by now!
django syncdb and an updated model
from that question/answer:
Django doesn't support migrations out
of the box. There is a pluggable app
for Django that does exactly that
though, and it works great. It's
called South.
http://south.aeracode.org/
Havent used django in a while, but i
seem to remember that syncdb does
perform alter commands on db tables.
you have to drop the table then run
again and it will create again.
In django models say this model exist in details/models.py
class OccDetails(models.Model):
title = models.CharField(max_length = 255)
occ = models.ForeignKey(Occ)
So when sync db is made the following fields get created
and later to this of two more fields are added and sync db is made the new fields doesnt get created.How is this to be solved,Also what is auto_now=true in the below
these are the new fields
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True, auto_now=True)
syncdb creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created.
Syncdb will not alter existing tables
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
you can either
Issue a manual ALTER TABLE command
DROP TABLE the particular table (will lose data) and run syncdb again
run django-admin sqlclear to get a list of sql statements to clear the entire db and run those commands (will flush the db - you'll lose all existing data) or
DateField.auto_now: automatically set the field to NOW() every time the object is saved. Useful for "last-modified" timestamps. Note that the current date is always used; it's not just a default value that you can override.
Thus, the modified_date column will be automatically updated every time you call object.save()
This is a common problem with Django. As said by Amarghosh, syncdb can not modify the schema of existing tables.
South has been created to solve this problem.
I do recommend it.