尝试保存模型实例时的KeyError。 它必须对post_save信号作出反应而不是保存实例......
代码:
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).order_by('order')
entrys[0].save()
post_save.connect(playlist_entry_changed, PlaylistEntry)
错误:
Exception Type: KeyError at /admin/playlist/playlistentry/add/
Exception Value: 38539456
答案 0 :(得分:1)
根据您的评论,您要做的是更新订购。而不是使用信号,重写保存方法。
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)
另外,为什么默认你的订单为900万......你不应该从0开始吗?
答案 1 :(得分:0)
要实现订购,您还可以查看this snippet!