i am getting a relation does not exist and I cant find a solution.
error:relation "sales_Oeslshstsql" does not exist
LINE 1: SELECT * FROM "sales_Oeslshstsql
(app name is sales)
model:
class Oeslshstsql(models.Model):
hst_prd = models.SmallIntegerField()
hst_year = models.SmallIntegerField()
cus_no = models.CharField(max_length=12)
item_no = models.CharField(max_length=15)
.....
a4glidentity = models.IntegerField(db_column='A4GLIdentity', primary_key = True)
class Meta:
managed = False
db_table = 'OESLSHST_SQL'
def __str__(self):
return (self.hst_year)
View:
def sales(request):
#sales_list = Oeslshstsql.objects.all().order_by('hst_year','hst_prd').reverse()
s = Oeslshstsql.objects.raw('SELECT * FROM "sales_Oeslshstsql"')
sales_list = s
return render(request,'saleslist.html',{'sales_list':sales_list})
The error is raised when s is evaluated. I tried switching cases in the select and messed with migrations no luck.
I am migrating an existing app to Django using a postgres backend, any help would be appreciated.
try:
s = Oeslshstsql.objects.raw('SELECT a4glidentity as id, ... , FROM "OESLSHST_SQL"')
http://docs.djangoproject.com/en/1.8/ref/models/options/#db-table seems your tablename in query is wrong
edit: you should add the primary key as id see https://docs.djangoproject.com/en/1.8/topics/db/sql/#mapping-query-fields-to-model-fields
Hi I had the same issue migrating an existing app to 1.11. The only solution I found was ....
Clear all all files from the app's migrations dir leaving only the init.py file
Make sure that the admin.py file is empty
Run manage.py makemigrations
Run manage.py sqlmigrate <app_label> 0001
copy the sql output
using pgAdminIII select "Execute arbitrary SQL queries"
Paste and execute the SQL statements in pgAdminIII
This was the only solution I could find, bit of a hack true, but worked. Hope it helps.This would also work via psql terminal I suppose, but I used pgAdmin
Related
I unintentionally created a model with a field "id" and did the migration. The model at first looked like this:
class VsSession(models.Model):
id = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Afterwards I rename the field to vs_session:
class VsSession(models.Model):
vs_session = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Now whenever I try to use the model e.g., like this:
def get(self, request):
try:
sessionid = uuid.uuid4()
new_session = VsSession(vs_session=sessionid, state="active")
new_session.save()
return Response({'success': 'true', 'vssession': sessionid})
except Exception as e:
print(str(e))
return Response({'success': 'false'})
I get this error:
VsSession() got an unexpected keyword argument 'vs_session'
Can anybody please tell me what I did wrong and how to fix this.
Thank you very much!
So I have no idea why this is working now, but I fixed it. What I did is
Removed vs_session variable from the model
Added created_at = models.DateTimeField(auto_now_add=True) to the model
makemigration and migrate
Run code/stop code
Add vs_session variable to model
makemigration an migrate
Everything is fine :)
Did you try running python manage.py makemigrations? After running this you should see a message telling you the field was renamed. To actually apply the migration to your database you can run python manage.py migrate
I'm having trouble creating a model in django. I wrote a model like this:
from django.db import models
class FooModel(models.Model):
name = models.CharField(max_length = 255)
I run
manage.py syncdb
But when I'm in the shell, I can't save an instance. Every time I call it, it tells me it's missing a column
manage.py shell
>>from app.models import FooModel
>>foo = FooModel()
>>foo.name = 'foo'
>>foo.save()
DatabaseError: column "name" of relation "ecommerce_foomodel" does not exist
LINE 1: INSERT INTO "ecommerce_foomodel" ("name") VALUES (E'123123as...
We're using postgres.
The database table was created before you added the corresponding fields.
So, you can recreate all of the tables of that app (in case you don't have any useful data) using:
python manage.py reset ecommerce
Or, you should migrate the database to the latest version using South.
I am getting an DatabaseError saying no column named playlist exists and I'm trying to figure out how to fix it. I'm using South. I deleted the old files in the my migrations folder and ran:
python manage.py schemamigration app_name --initial
python manage.py migrate reserve
I get this error when I do that:
south.exceptions.GhostMigrations:
! These migrations are in the database but not on disk:
<reserve: 0002_initial>
! I'm not trusting myself; either fix this yourself by fiddling
! with the south_migrationhistory table, or pass --delete-ghost-migrations
! to South to have it delete ALL of these records (this may not be good).
I'm not sure how to get rid of this error, since in my migrations folder I only have init.py(c) and 0001_initial.py(c); I don't have 0002 migration file anymore.
When I try runserver and click "add playlist" in the admin, this is when I get the DatabaseError. If it helps, my models.py is:
class UserProfile(models.Model):
user = models.OneToOneField(User)
def __unicode__(self):
return self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class Playlist(models.Model):
playlist = models.CharField('Playlist', max_length = 2000, null=True, blank=True)
def __unicode__(self):
return self.playlist
class Video(models.Model):
video_url = models.URLField('Link to video', max_length = 200, null=True, blank=True)
def __unicode__(self):
return self.video_url
class UserPlaylist(models.Model):
profile = models.ForeignKey(User)
playlist = models.ForeignKey(Playlist)
def __unicode__(self):
return self.playlist
class Videoplaylist(models.Model):
video = models.ForeignKey(Video)
playlist = models.ForeignKey(UserPlaylist)
def __unicode__(self):
return self.playlist
Any advice on how to fix this?
Just run
python manage.py migrate reserve --delete-ghost-migrations
This should remove non existing migration from the database table south_migrationhistory.
First, you should work out what happened to get the db and filesystem out of sync.
Then, if appropriate, you can do
python manage.py migrate reserve --ignore-ghost-migrations
or
python manage.py migrate reserve --delete-ghost-migrations
as Aidas said, whichever seems more appropriate. The ignore option is probably less risky, although something has already gone astray for you to get to this state.
South stores migration information in the database too, in a table called "migrations". [ I think thats the table name; writing this from memory ].
You need to clear that table out.
Note
Once you clear that table out, you have to start the migrations again from scratch; right from the initial migration.
It would be a good idea to make a copy of your database as-is before you do this. I assume that your code is already version controlled.
Usually this error happens because, you created a migration file and did the migration then, that migration file was deleted from your file system(disk)
So you have changes in your database caused by a migration that no longer exists.
Depending on whether you deleted the migration file file by choice, what you can do; is go ahead and also delete the changes from the database.
Start the python shell;
$ python manage.py shell
>>from south.models import MigrationHistory
>>MigrationHistory.objects.filter(migration='0002_initial').delete()
That will have deleted the 0002 migration from the db.
You can now go ahead and create/recreate the migration you want.
Goodluck,
Komu.
Just run the command where manage.py file is present in your directory
./manage.py migrate appname --delete-ghost-migrations
I wanted to add a table and a foreign key to that table. Initially I had:
class VirtualMachine(models.Model):
...
I then changed that to:
class OperatingSystem(models.Model):
name = models.CharField(max_length=40)
def __unicode__(self):
return self.name
class VirtualMachine(models.Model):
operating_system = models.ForeignKey(OperatingSystem, default=1)
and I wanted to make an entry so that 1 would be "WindowsXP". South didn't like that, though, so I changed the last line to:
operating_system = models.ForeignKey(OperatingSystem, null=True)
That worked ok. After that migration I added the "WindowsXP" entry and changed it back to:
operating_system = models.ForeignKey(OperatingSystem, default=1)
I did python manage.py schemamigration app --auto, which worked fine, then python manage.py migrate app, which froze. Froze!
I cancelled it and went into psql. I couldn't do SELECT * FROM app_virtualmachine; - that would hang, although getting stuff from other tables would not. I couldn't even select just a column from there. I tried dropping the constraint South added but also no good. What gives?
Ah I think the table got locked or something. I restarted postgres and then could do stuff manually to the table and rescue it.
I have two questions:
How do I delete a table in Django?
How do I remove all the data in the table?
This is my code, which is not successful:
Reporter.objects.delete()
Inside a manager:
def delete_everything(self):
Reporter.objects.all().delete()
def drop_table(self):
cursor = connection.cursor()
table_name = self.model._meta.db_table
sql = "DROP TABLE %s;" % (table_name, )
cursor.execute(sql)
As per the latest documentation, the correct method to call would be:
Reporter.objects.all().delete()
If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.
See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/
Using shell,
1) For Deleting the table:
python manage.py dbshell
>> DROP TABLE {app_name}_{model_name}
2) For removing all data from table:
python manage.py shell
>> from {app_name}.models import {model_name}
>> {model_name}.objects.all().delete()
Django 1.11 delete all objects from a database table -
Entry.objects.all().delete() ## Entry being Model Name.
Refer the Official Django documentation here as quoted below -
https://docs.djangoproject.com/en/1.11/topics/db/queries/#deleting-objects
Note that delete() is the only QuerySet method that is not exposed on a Manager itself. This is a safety mechanism to prevent you from accidentally requesting Entry.objects.delete(), and deleting all the entries. If you do want to delete all the objects, then you have to explicitly request a complete query set:
I myself tried the code snippet seen below within my somefilename.py
# for deleting model objects
from django.db import connection
def del_model_4(self):
with connection.schema_editor() as schema_editor:
schema_editor.delete_model(model_4)
and within my views.py i have a view that simply renders a html page ...
def data_del_4(request):
obj = calc_2() ##
obj.del_model_4()
return render(request, 'dc_dash/data_del_4.html') ##
it ended deleting all entries from - model == model_4 , but now i get to see a Error screen within Admin console when i try to asceratin that all objects of model_4 have been deleted ...
ProgrammingError at /admin/dc_dash/model_4/
relation "dc_dash_model_4" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM "dc_dash_model_4"
Do consider that - if we do not go to the ADMIN Console and try and see objects of the model - which have been already deleted - the Django app works just as intended.
django admin screencapture
Use this syntax to delete the rows also to redirect to the homepage (To avoid page load errors) :
def delete_all(self):
Reporter.objects.all().delete()
return HttpResponseRedirect('/')
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
First, install django-turncate using your terminal/command line:
pip install django-truncate
Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
...
'django_truncate',
]
Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance1 = SomeModel.objects.get(id=id)
instance1.delete()
// don't use same name
Actually, I un-register the model (the table data that I want to delete) from the admin.py. Then I migrate.
python manage.py makemigrations
python manage.py migrate
python runserver
Then I register the model in the admin.py and do migration again. :) Now, the table is empty. This might not be a professional answer, but it helped me.