KeyError when trying to save model instance. Django
KeyError when trying to save model instance. It has to react on post_save signal than save instance...
Code:
from django.db.models.signals import post_save
class PlaylistEntry(models.Model):
playlist=models.ForeignKey(Playlist)
media=models.ForeignKey(Media)
order=models.PositiveIntegerField(default=9000000, editable=False)
added=models.DateTimeField(default=datetime.datetime.now(),editable=False )
def playlist_entry_changed(sender, instance, **kwargs):
entrys=PlaylistEntry.objects.filter(playlist=instance.playlist).开发者_如何学Corder_by('order')
entrys[0].save()
post_save.connect(playlist_entry_changed, PlaylistEntry)
Error:
Exception Type: KeyError at /admin/playlist/playlistentry/add/
Exception Value: 38539456
From your comments what you're trying to do is update ordering. Rather than use a signal, override the save method.
def save(self, *args, **kwargs):
# Only do this if it's the first time we're saving.
if not self.id:
entries = PlaylistEntry.objects.order_by('-order')
try:
self.order = entries[0].order + 1
except IndexError:
# we don't have any PlaylistEntries yet, so we just start @ 0
self.order = 0
super(PlaylistEntry, self).save(*args, **kwargs)
Also, why are default your order to 9 million... shouldn't you start with 0?
For implementig an ordering you can also have a look at this snippet!
精彩评论