Sammy Kim
Sammy Kim

Reputation: 113

how to delete forien-key Imagefield in django?

I am already using django-cleanup. But it works when imagefield was deleted. If imagefield is realted to a model like below. As long as I don't delete imagefield manually, It can't be working.

from django.db import models

class Listing(models.Model):
    title = models.CharField(max_length=25)


class ListingImages(models.Model):
    listing = models.ForeignKey(Listing, default=None)
    image = models.ImageField()

Listing can have many images which isn't fixed quantities. So I implemented like that. But now I have a problem with how I can find which image should be deleted. Lazy algorithm is just iterate every image data when post or put request. and delete not matched image which is related to Listing object.

But it's too expensive I think. Is there any good solution? I was searching that 'delete foreign key image in django' this keyword. But there is no solution for me.

Upvotes: 0

Views: 56

Answers (1)

Prabhakaran
Prabhakaran

Reputation: 3993

You can use your primary key id of ListingImages model with DELETE method to remove it. Django provides handy CRUD operations.

What you mentioned in your comment was correct. Proceed with pk it should work.

Upvotes: 1

Related Questions