简体   繁体   English

django中的post_save立即更新实例

[英]post_save in django to update instance immediately

I'm trying to immediately update a record after it's saved. 我正在尝试在保存后立即更新记录。 This example may seem pointless but imagine we need to use an API after the data is saved to get some extra info and update the record: 这个例子看似毫无意义,但想象一下,我们需要在保存数据后使用API​​来获取一些额外的信息并更新记录:

def my_handler(sender, instance=False, **kwargs):
    t = Test.objects.filter(id=instance.id)
    t.blah = 'hello'
    t.save()

class Test(models.Model):
    title = models.CharField('title', max_length=200)
    blah = models.CharField('blah', max_length=200)

post_save.connect(my_handler, sender=Test)

So the 'extra' field is supposed to be set to 'hello' after each save. 所以'extra'字段应该在每次保存后设置为'hello'。 Correct? 正确? But it's not working. 但它不起作用。

Any ideas? 有任何想法吗?

When you find yourself using a post_save signal to update an object of the sender class, chances are you should be overriding the save method instead. 当您发现自己使用post_save信号更新发送方类的对象时,您可能应该覆盖save方法。 In your case, the model definition would look like: 在您的情况下,模型定义将如下所示:

class Test(models.Model):
    title = models.CharField('title', max_length=200)
    blah = models.CharField('blah', max_length=200)

    def save(self, force_insert=False, force_update=False):
        if not self.blah:
            self.blah = 'hello'
        super(Test, self).save(force_insert, force_update)

Doesn't the post_save handler take the instance? post_save处理程序不接受实例吗? Why are you filtering using it? 你为什么用它过滤? Why not just do: 为什么不这样做:

def my_handler(sender, instance=False, created, **kwargs):
  if created:
     instance.blah = 'hello'
     instance.save()

Your existing code doesn't work because it loops, and Test.objects.filter(id=instance.id) returns a query set, not an object. 您的现有代码不起作用,因为它循环,并且Test.objects.filter(id=instance.id)返回查询集,而不是对象。 To get a single object directly, use Queryset.get() . 要直接获取单个对象,请使用Queryset.get() But you don't need to do that here. 但你不需要在这里这样做。 The created argument keeps it from looping, as it only sets it the first time. 创建的参数使其不会循环,因为它只是第一次设置它。

In general, unless you absolutely need to be using post_save signals, you should be overriding your object's save() method anyway. 通常,除非您绝对需要使用post_save信号,否则无论如何都应该覆盖对象的save()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM