M
M
matveyvarg2017-06-13 17:02:57
Django
matveyvarg, 2017-06-13 17:02:57

How to add ManyToMany using perform_update?

Model Part :

class Entry(models.Model):

    user = models.ForeignKey(User, related_name='entries')
    drivers = models.ManyToManyField(Driver, related_name='entries', blank=True, null=True)
    ...

Serializer:
class EntrySerializer(serializers.ModelSerializer):

    class Meta:
        model = Entry
        fields = '__all__'
        extra_kwargs = {'user': {'read_only': True}, 'driver': {'read_only': True}}

view:
class SetAsDriver(generics.UpdateAPIView):
    permission_classes = (IsAuthenticated, IsDriver)
    queryset = Entry.objects.all()
    serializer_class = EntrySerializer

I'm trying to understand how it is possible to add one more to the drivers objects using perform_update. For example, you should get something like:
class SetAsDriver(generics.UpdateAPIView):
    permission_classes = (IsAuthenticated, IsDriver)
    queryset = Entry.objects.all()
    serializer_class = EntrySerializer

    def perform_create(self,serializer):
        serializer.data.drivers.add(self.request.user.driver)
        serializer.save()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question