Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested field serializer - Data missing

Related to this Topic


Hi, I cannot follow the answer at the attached topic, because an ID is missing after serialization.

  • Model.py

class Owner(models.Model):
    name = models.CharField(db_index=True, max_length=200)

class Car(models.Model):
    name = models.CharField(db_index=True, max_length=200)
    LCVS  = models.ForeignKey(Owner)
  • View.py

class OwnerViewSet(viewsets.ModelViewSet):
    queryset = Owner.objects.all()
    serializer_class = OwnerSerializer

class CarViewSet(viewsets.ModelViewSet):
    serializer_class = CarSerializer
    queryset = Car.objects.all()
  • Serializer.py

class OwnerSerializer(serializers.ModelSerializer):
    class Meta:
        model =  Owner
        fields = ('id', 'name')

class CarSerializer(serializers.ModelSerializer):
    owner = OwnerSerializer() 

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

    def create(self, validated_data):
        tmp_owner = Owner.objects.get(id=validated_data["car"]["id"])
        car = Car.objects.create(name=self.data['name'],owner=tmp_owner)
        return car

Now i send the following request :

Request URL:http://localhost:9000/api/v1/cars
Request Method:POST
Request Paylod :
{
    "name": "Car_test", 
    "ower": {
        "id":1,
        "name": "Owner_test"
    }
}

But, here the validated_data don't contain the owner ID !

Traceback | Local vars

 validated_data {u'Owner': OrderedDict([(u'name', u'Owner_test')]), u'name': u'Car_test'} 

@Kevin Brown :
Workful ! Thanks I'll validate your answer but I get a new problem...

Now when I try to put a new Owner, an error raise :

{
    "id": [
        "This field is required."
    ]
}

I had to create a new serializer ?

like image 609
CheapD AKA Ju Avatar asked Jan 09 '15 10:01

CheapD AKA Ju


1 Answers

Any AutoFields on your model (which is what the automatically generated id key is) are set to read-only by default when Django REST Framework is creating fields in the background. You can confirm this by doing

repr(CarSerializer())

and seeing the field generated with read_only=True set. You can override this with the extra_kwargs Meta option which will allow you to override it and set read_only=False.

class OwnerSerializer(serializers.ModelSerializer):

    class Meta:
        model =  Owner
        fields = ('id', 'name')
        extra_kwargs = {
            "id": {
                "read_only": False,
                "required": False,
            },
        }

This will include the id field in the validated_data when you need it.

like image 180
Kevin Brown-Silva Avatar answered Oct 12 '22 06:10

Kevin Brown-Silva