簡體   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