How to get object instance inside to_internal_value()?

1,461 views
Skip to first unread message

Rahul Sarma

unread,
May 23, 2019, 5:21:58 AM5/23/19
to Django REST framework
Hi, I am writing a custom field. I am doing validation inside the to_internal_value() method for which I need the object instance. I'm able to get it in the to_representation() method as "value" argument. How do I also access it inside the to_internal_value() method?

class OptionField(serializers.Field):

    def to_representation(self, value):
        selected_options = Option.objects.filter(
                optiongroup__question=value).distinct()
        return OptionSerializer(selected_options, many=True).data

    def to_internal_value(self, data):
        options = []
        if not isinstance(data, list):
            raise ValidationError(
                "Incorrect type of options. Expected a list."
                f" Got {type(data).__name__}.")

        for item in data:
            if not isinstance(item['id'], six.integer_types):
                raise ValidationError(
                    "Incorrect id type of Option. Expected int. "
                    f"Got {type(item['id']).__name__}.")

            try:
                option = Option.objects.get(pk=item['id'])
            except Option.DoesNotExist:
                raise ValidationError("Option matching query does not exist.")

            options.append(option)
        return {'options': options}


class QuestionSerializer(serializers.ModelSerializer):
    options = OptionField(source='*')

    class Meta:
        model = Question
        fields = ('content', 'options')
        read_only_fields = ('content',)


attipati kumar

unread,
May 24, 2019, 1:36:11 AM5/24/19
to django-res...@googlegroups.com

I thing you don't want to use the save() method. You can always write down for e.g., like this.

class PointSerializer:
    def save(self):
        self.instance = Point(self.validated_data)
        return self.instance

s = PointSerializer(...)
s.is_valid(raise_exception=True)
instance = s.save()
or
You want do instead look like:
my_serializer.is_valid(raise_exception=True)
instance = my_serializer.save()
And also you have a guide with this link's, can you follow it.
1)  http://www.django-rest-framework.org/api-guide/fields/#custom-fields
2)  https://github.com/encode/django-rest-framework/blob/90ed2c1ef7c652ce0a98075c422d25a632d62507/rest_framework/serializers.py#L468-L471





Mailtrack Sender notified by
Mailtrack 05/24/19, 10:59:19 AM

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/e6cd5749-4092-4d8a-b1a3-ec42ce56b520%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


--
Thanks & Regards
Kumar A

Reply all
Reply to author
Forward
0 new messages