Django - How to fix model with id field - python

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

Related

django states attibuteError although attribute is assigned

I have a Payment Django model that has a CheckNumber attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the str method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error message:
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
this is my code:
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
I would absolutely love any comments/suggestions about the cause of the error
In my opinion, you have introduced CheckNumber field in the Payment models recently with no migration. make sure you run the migration then you can do that using the following command.
python manage.py migrate
This will create a new field in the Payment table. Hopefully, this will resolve your issue.
please clean the database and then run the migration command.
To clean the database you need to write the following command(Don't run this command in production):
python manage.py flush
After the cleaning, you can make an initial migration using the following command:
python manage.py makemigrations
and then migrate those changes to the database table:
python manage.py migrate
So it turns out that when you pass a name value in a model field, it changes the name of the field with it, I personally thought that it would change the name when displayed in the Django admin. My fix was to just remove the name value and migrate, that fixed it for me.

Django RelatedObjectDoesNotExist After Upgrade to 2.2

I've recently upgraded one of my Django projects from 1.9.6 to 2.2 and in doing so I'm getting a strange error around a specific ForeignKey relation.
models.py
class MyObject1(models.Model):
myobject2 = models.ForeignKey(MyObject2, on_delete = models.CASCADE)
views.py
def my_view(request, id):
try:
my_object = MyObject1.objects.get(id = id)
except:
# do some stuff
else:
print (my_object.myobject2)
result
RelatedObjectDoesNotExist
MyObject1 has no myobject2
at line print (my_object.myobject2)
I have confirmed via the Django shell that the instance in question does have a valid myobject2 and I don't get that error when performing the same actions in the shell.
All other ForeignKey relations in the application work as expected except for this one.
This is quite puzzling and all help is appreciated. Thanks!

Django raw raises relation does not exist

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

Django Model IntegrityError: NOT NULL constraint failed:

I am building a service that makes short URLs. I have the models:
from django.db import models
class ShortURL(models.Model):
url = models.CharField(max_length = 50)
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
I have already run the command: python manage.py migrate
If I open the interpreter, using python manage.py shell and run this code:
>>> from appshort.models import LongURL
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
then I get the error:
django.db.utils.IntegrityError: NOT NULL constraint failed: appshort_longurl.url_to_short_id
What did I do wrong?
class LongURL(models.Model):
name = models.CharField(max_length = 100, null=True)
url_to_short = models.ForeignKey(ShortURL)
The way you have set it up, the url_to_short foreign key is not optional. So when you try to save:
>>> a = LongURL(name = 'hello_long_link')
>>> a.save()
Django is trying to tell you that you didn't provide the url_to_short relation on your a model instance.
You'll need to either
Provide the ShortURL relation when you create the LongURL instance
Make the url_to_short relation optional with null=True, blank=True.
While creating an entry for LongURL you must create an object of ShortURL or filter out already existing (because ForeignKey field cannot be left blank). Additionally, you say that sometimes you have been able to achieve the desired behaviour. This can be so because at those places you would have got an object of ShortURL which is not null. However, the error in the discussion arises, when you try to send a null object during the creation of LongURL. For example:
...
short_url_obj = ShortURL.objects.filter(...).first()
# you have to ensure that this above query is not null
try:
new_long_url = LongURL(url_to_short=short_url_obj, name="some_name")
new_long_url.save()
except:
# if the short_url_obj is null
print("The short_url_obj was null, cannot save to database")
...
One can also use if-else block instead, but I would not advice that.

How to fix a Database Error and ghost migration error in Django?

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

Categories

Resources