繁体   English   中英

更新Django post_save信号中certail列的值

[英]Update value of a certail column in django post_save signals

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

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''

和signals.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

我想按照以上在post_save信号中说明的那样更新video_mp4的值。 请让我知道如何实现这一目标。 我收到以下错误

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']

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()

UPDATE
上述解决方案将导致maximum recursion depth exceeded while calling a Python object错误时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''

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

谢谢@杰林·彼得·乔治但是找到了一个很好的解决方案

检查一下

暂无
暂无

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

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