optimizing django code model -
optimizing django code model -
i want optimizing code. think best solution utilize method pre_save , not override save method. function delete old image when in editing upload new image
def delete_old_image(sender, instance): try: obj = sender.objects.get(id=instance.id) except sender.doesnotexist: pass else: if not obj.image == instance.image: try: os.remove(obj.image.path) except: pass
under code of model
class service(models.model): title= models.charfield(max_length=170) slug = models.slugfield(max_length=200, blank=true, unique=true, editable=false) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(service, self).save(*args, **kwargs) class portfoglio(models.model): title= models.charfield(max_length=170, unique=true) slug = models.slugfield(max_length=200, blank=true, unique=true, editable=false) image=models.imagefield(upload_to = 'images/' , default= 'images/foto.jpg', verbose_name='upload') def save(self, *args, **kwargs): self.slug = slugify(self.title) if self.id not none: delete_old_image(portfoglio, self) super(portfoglio, self).save(*args, **kwargs) class image(models.model): title= models.charfield(max_length=200) image=models.imagefield(upload_to = 'images/' , default= 'images/foto.jpg', verbose_name='upload') def save(self, *args, **kwargs): if self.id not none: delete_old_image(portfoglio, self) super(image, self).save(*args, **kwargs) class team(models.model): name= models.charfield(max_length=200) image= models.imagefield(upload_to = 'images/' , default= 'images/foto.jpg', verbose_name='upload') def save(self, *args, **kwargs): if self.id not none: delete_old_image(team, self) super(team, self).save(*args, **kwargs)
from django.db.models.signals import pre_save django.dispatch import receiver @receiver(pre_save) def pre_delete_old_image(sender, instance, created, **kwargs): if sender not in [service, portfoglio, image, team]: homecoming if getattr(sender, 'slug', false): instance.slug = slugify(instance.title) if not created , getattr(sender, 'image', false): delete_old_image(sender, instance) def delete_old_image(sender, instance): try: obj = sender.objects.get(id=instance.id) except sender.doesnotexist: pass else: if obj.image != instance.image: try: os.remove(obj.image.path) except exception e: pass
django django-models model save
Comments
Post a Comment