Home > Net >  How to delete corresponding row with ManyToMany relationship in Django?
How to delete corresponding row with ManyToMany relationship in Django?

Time:09-10

I am trying to make a basic pizza app with two API's, toppings and pizzas. When I delete a topping, I would like for the corresponding pizzas to also be deleted since the topping is no longer available. As it currently stands, when I delete a topping it just keeps an empty pizza object.

Models:

class Toppings(models.Model):
    name = models.CharField(max_length=60, unique=True)

    def __str__(self):
        return self.name


class Pizza(models.Model):
    name = models.CharField(max_length=60, unique=True)
    topping = models.ManyToManyField(Toppings, max_length=60, related_name="toppings")

    def __str__(self):
        return (self.name, self.topping)

Serializers:

class PizzaSerializer(serializers.ModelSerializer):
    toppings = ToppingsSerializer(read_only=True, many=True)

    class Meta:
        model = Pizza
        fields = "__all__"
class ToppingsSerializer(serializers.ModelSerializer):

    class Meta:
        model = Toppings
        fields = "__all__"

Pizza.views and Toppings.views are almost the same so I just included Pizza.

class PizzaList(generics.ListAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer


class PizzaCreate(generics.CreateAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer


class PizzaUpdate(generics.UpdateAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer


class PizzaDelete(generics.DestroyAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer

Please let me know if you need anything else. Thank you.

CodePudding user response:

ManyToMany by itself does not handle automatic deletion protocols since it does not have sense; It's designed to permit related instances on both sides. What you could do here are various approaches to accomplish what you want, what I'd suggest is to configure a pre_delete signal on your Toppings model that deletes all of its related Pizzas before being deleted. Also, I would recommend to decouple your M2M relationship and define it as a through model for a cleaner approach and more granular control over your M2M data structure (but this is just my personal opinion and style).

  • Related