尝试保存模型实例时发生 KeyError。姜戈

发布于 2024-09-16 07:13:52 字数 766 浏览 3 评论 0原文

尝试保存模型实例时发生 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

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).order_by('order')
        entrys[0].save()

post_save.connect(playlist_entry_changed, PlaylistEntry)

Error:

Exception Type: KeyError at /admin/playlist/playlistentry/add/
Exception Value: 38539456

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

去了角落 2024-09-23 07:13:52

根据您的评论,您想要做的是更新排序。不要使用信号,而是重写 save 方法。

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开始吗?

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?

这个俗人 2024-09-23 07:13:52

要实现排序,您还可以查看此代码段

For implementig an ordering you can also have a look at this snippet!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文