nielsrolf
nielsrolf

Reputation: 81

Get post data from CustomField in django rest framework

To make it short: I have a serializer (django rest framework) that has two custom fields which do not directly correspond to a field of my model and also have a different name. The to_internal_value() method (probably) works, but I don't know how to access the post data of these fields.

And in case you need more details on my case:

I have a django model that looks like this:

class Requirement(models.Model):
    job         = models.ForeignKey('Job', related_name = 'requirements')
    description = models.CharField(max_length = 140)
    is_must_have = models.BooleanField() # otherwise is of type b

class Job(models.Model):
    ...

I want to serialize it in a manner that a job object will look like this:

{ "must_have": [must have requirements], "nice:to_have": [nice to have requirements] }

Therefore, I have custom fields in my serializer for jobs:

class JobSerializer(serializers.Serializer):
    nice_to_have = NiceToHaveField(source = 'requirements', allow_null = True)
    must_have = MustHaveField(source = 'requirements', allow_null = True)

The NiceToHaveField and the MustHaveField classes simpy override the to_representation() and the to_internal_value() methods, the to_representation also sorts the requirements after type. But the validated_data in JobSerializer.create never contain these cutom fields. I know the to_internal_value gets called and does its work, but the results are not accessable.

What is the way to solve this?

Upvotes: 0

Views: 912

Answers (1)

nielsrolf
nielsrolf

Reputation: 81

I found a solution I don't like, there is probably a better way to do this. Anyways, the data is available in the view.request.data. So I used the perform_create hook like this:

def perform_create(self, serializer):    
    nice_to_have = None
    must_have = None
    if 'nice_to_have' in self.request.data and self.request.data['nice_to_have'] != None:
        field = NiceToHaveField()
        nice_to_have = field.to_internal_value(self.request.data['nice_to_have'])

    if 'must_have' in self.request.data and self.request.data['must_have'] != None:
        field = MustHaveField()
        must_have = field.to_internal_value(self.request.data['must_have'])

    serializer.save(owner = self.request.user, nice_to_have = nice_to_have, must_have = must_have)      

Upvotes: 1

Related Questions