A
A
Alexander2016-08-24 02:32:54
Django
Alexander, 2016-08-24 02:32:54

How to delete all files associated with a model?

Tell me how to remove the ad and all the photos attached to it?
Here are the models

class Advert(models.Model):
    user = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=30)
    ad_type = models.CharField(max_length=30)
    category = models.TextField()
    title = models.CharField(max_length=64)
    sex = models.CharField(max_length=7)
    description = models.CharField(max_length=2000)

class AdvertPhoto(models.Model):
    advert = models.ForeignKey('Advert')
    photo = models.ImageField(upload_to='')
    preview = models.BooleanField(default=False)

    def __str__(self):
        return str(self.advert)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2016-08-24
@AlexMine

Tons of options. For example:

from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
@receiver(pre_delete, sender=AdvertPhoto)
def advert_photo_delete(sender, instance, **kwargs):
    instance.file.delete(False)

import os
for instance in AdvertPhoto.objects.all():
    os.remove(instance.photo.path)

What exactly needs to be achieved?

V
VadimChin, 2016-08-24
@VadimChin

https://github.com/un1t/django-cleanup
stackoverflow.com/questions/5372934/how-do-i-get-d...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question