首页 > 解决方案 > 更新 django post_save 信号中 certail 列的值

问题描述

我有一个类视频,其结构如下:

class Video(models.Model):
    video = models.FileField(upload_to="media_items/video", blank=True)
    video_mp4 = models.CharField(blank=True, max_length=500)

    def __unicode__(self):
        return unicode(self.video.name) or u''

和信号.py 是

@receiver(post_save, sender = Video)
def insert_video_mp4(sender, instance, created, **kwargs):
    if os.path.exists(created_path):
        #some code
    else:
        #some code to insert value in video_mp4 column

我想更新 video_mp4 的值,如上面 post_save 信号中所述。请让我知道如何实现这一目标。我收到以下错误

RuntimeError at /admin/blog/video/8/change/
maximum recursion depth exceeded while calling a Python object
Request Method: POST
Request URL:    http://localhost:8000/admin/blog/video/8/change/
Django Version: 1.10.5
Exception Type: RuntimeError
Exception Value:    
maximum recursion depth exceeded while calling a Python object
Exception Location: /Users/anaconda2/lib/python2.7/site-packages/django/db/models/fields/__init__.py in __eq__, line 462
Python Executable:  /Users/anaconda2/bin/python
Python Version: 2.7.15
Python Path:    
['/Users/TechnopleSolutions/Desktop/matrix-server-master',
 '/Users/anaconda2/lib/python27.zip',
 '/Users/anaconda2/lib/python2.7',
 '/Users/anaconda2/lib/python2.7/plat-darwin',
 '/Users/anaconda2/lib/python2.7/plat-mac',
 '/Users/anaconda2/lib/python2.7/plat-mac/lib-scriptpackages',
 '/Users/anaconda2/lib/python2.7/lib-tk',
 '/Users/anaconda2/lib/python2.7/lib-old',
 '/Users/anaconda2/lib/python2.7/lib-dynload',
 '/Users/anaconda2/lib/python2.7/site-packages',
 '/Users/anaconda2/lib/python2.7/site-packages/aeosa']

标签: pythondjango

解决方案


instance是这里的对应Video对象。


@receiver(post_save, sender = Video)
def insert_video_mp4(sender, instance, created, **kwargs):
    if os.path.exists(created_path):
        #some code
    else:
        instance.video_mp4="some value"
        instance.save()

更新
上述解决方案将导致maximum recursion depth exceeded while calling a Python object错误。所以,通过覆盖它来做你的模型逻辑save()方法,

class Video(models.Model):
    video = models.FileField(upload_to="media_items/video", blank=True)
    video_mp4 = models.CharField(blank=True, max_length=500)

    def save(self, *args, **kwargs):
        if os.path.exists(created_path):
        # some code
        else:
            self.video_mp4 = "some text"
        super().save(*args, **kwargs)

    def __unicode__(self):
        return unicode(self.video.name) or u''

注意:在信号中调用.save()方法不是一个好主意post_save


推荐阅读