9
9
95506682020-08-26 11:39:46
Django
9550668, 2020-08-26 11:39:46

Django. DRF. Serializers. How to pass an additional variable to the serializer during initialization?

Good afternoon everyone!

There is a code:

class TestUpdateApiView(generics.RetrieveUpdateDestroyAPIView, TestCustomMixin):
    serializer_class = TestSerializer
    queryset = Test.objects.all()
    lookup_field = "id"


How to make it so that I can transfer the User accessing this CBV to the serializer?

For example, how to do something like this:
serializer_class = TestSerializer(user=self.user)
And then in the serializer:
def update(self, instance, validated_data):
        #self.instance.id -  ID записи на апдейт
        if self.instance.id.creator == {переменная пользователя, передаваямая в Сериалайзер}
                 ret = super().update(instance, validated_data)
                 return ret
        ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JRazor, 2020-08-26
@9550668

What?
self.instance.id.creator
instance - this is the very object from where you need to take the data.
If it’s so hot to make a comparison (it’s not clear which one, but let it be), then you can create a property in user and check it there:

class User:
    @property
    def is_creator(self):
        # code

def update(self, instance, validated_data):
        if instance.is_creator:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question