Django覆盖保存

时间:2011-05-03 17:19:04

标签: django model save

我想在我的模型中覆盖save方法来创建适当的slug并创建imagefield的副本,并在其中进行少量修改。我该怎么办呢?

def save(self, *args, **kwargs):
            super(MyModel, self).save(*args, **kwargs) #to get id

            #slug
            self.slug = '%s-%i' % (self.topic, self.id)

            #create copy of img
            cp_path = dirname(self.image.path)+'/copies_'+basename(self.image.path)
            shutil.copy2(self.image.path, cp_path)

            file = open(cp_path)
            django_file = File(file)
            django_file.name = basename(cp_path) #otherwise path will be duplicated
            self.cp_image = django_file

            super(MyModel, self).save(*args, **kwargs) #to save my new ImageField

            create_watermark(self.cp_image, self.topic, self.text, 500, 45)

因为我使用super(MyModel,self).save()两次我有一个self.image文件的副本。如你所见,我对django和python不是很熟悉。我怎么能做得更好?

1 个答案:

答案 0 :(得分:1)

这可能不是最优雅的方式,但您可以尝试将save()post_save signal结合使用。可能看起来像:

class MyModel(Model):
    ## Stuff
    def save(self, *args, **kwargs):
        #create copy of img.  Fixed up to use string formatting.
        cp_path = "%s/copies_%s" % 
            (dirname(self.image.path), basename(self.image.path))
        shutil.copy2(self.image.path, cp_path)
        file = open(cp_path)
        django_file = File(file)
        django_file.name = basename(cp_path)
        self.cp_image = django_file
        create_watermark(self.cp_image, self.topic, self.text, 500, 45)
        super(MyModel, self).save(*args, **kwargs) #to save my new ImageField

from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=MyModel)
def mymodel_slug_handler(sender, instance=None, **kwargs):
    if instance is not None:
        new_slug = '%s-%i' % (instance.topic, instance.id)
        if instance.slug != new_slug: # Stops recursion.
            instance.slug = new_slug
            instance.save()