Home > OS >  Update array of ManyToMany field in Django REST framework
Update array of ManyToMany field in Django REST framework

Time:05-07

I have a Model Plot which looks like this:

from django.db import models


class Plot(models.Model):
    class SUNSHINE(models.TextChoices):
        NONE = None
        FULL_SUN = 'Plein soleil',
        SHADOW = "Dans l'ombre",
        SUNNY = 'Ensoleillée',
        MODERATE = 'Modérée'

    name = models.CharField(max_length=50)
    garden = models.ForeignKey('perma_gardens.Garden', on_delete=models.CASCADE)
    width = models.CharField(max_length=50, blank=True, null=True)
    height = models.CharField(max_length=50, blank=True, null=True)

    exposition = models.CharField(max_length=50, choices=SUNSHINE.choices, default=SUNSHINE.NONE, blank=True,
                                  null=True)

    qr_code = models.CharField(max_length=50, blank=True, null=True)

    plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant', blank=True)

    def __str__(self):
        return self.name

With a plant object which is a foreign key of the model of the same name. And I have this partial_update function in my view:

class PlotViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = Plot.objects.all()

    def partial_update(self, request, *args, **kwargs):
        instance = self.queryset.get(pk=kwargs.get('pk'))
        serializer = WritePlotSerializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

But when, in my front, I want to update the plants in my plot, I can select several of them and when I click on add it works it updated, but it deleted the old plants present or I would like that when I update, it keeps the plants that were already present in the array then it adds the one we just added. How can I do to get this result?

Here is my serializer of Plot model :

from rest_framework import serializers
from .models import Plot
from apps.perma_plants.models import Plant
from apps.perma_gardens.models import Garden
from apps.perma_plant_categories.models import PlantCategory


class GardenSerializer(serializers.ModelSerializer):

    class Meta:
        model = Garden
        fields = ('id', 'name',)

class PlantSerializer(serializers.ModelSerializer):
    class Meta:
        model = Plant
        fields = ('id', 'name', "category", 'image', 'facility_rate', 'sunshine_index', 'irrigation_index')

class ReadPlotSerializer(serializers.ModelSerializer):
    garden = GardenSerializer(required=True)
    plant = PlantSerializer(many=True)
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = Plot
        fields = '__all__'
        read_only_fields = [fields]

class WritePlotSerializer(serializers.ModelSerializer):

    class Meta:
        model = Plot
        fields = '__all__'

Thank you for your feedback!

CodePudding user response:

There are a couple of ways to solve this:

1- send the entire array in the request

2- add logic to the serializer using some validator. Refer to https://stackoverflow.com/a/66293267/9459826

UPDATE: I've removed #3 as I forgot SerializerMethodField is read-only. I'm sorry.

Docs: https://www.django-rest-framework.org/api-guide/serializers/#validation

  • Related