简体   繁体   中英

django-rest-framework- accepting id for submitted foreign key field

I have the following models:

class Parent(models.Model):
    name = models.CharField()

class Child(models.Model):
    name = models.CharField()
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)

with serializer:

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child
        fields = ('id', 'name', 'parent',)
        read_only_fields = ('id',)

and ModelViewSet:

class ChildViewSet(viewsets.ModelViewSet):
    serializer_class = ChildSerializer
    permission_classes = (IsAuthenticated,)
    queryset = Child.objects.all()
    paginator = None

If I query the api, I get a json structure that looks like:

{
  "id": 1,
  "name": "Child Name",
  "parent": 3
}

Which is exactly what I want. However, if I try to PUT the same data back, I get the error: ValueError: Cannot assign "3": "Child.parent" must be a "Parent" instance.

How can I make a submission like this work? I should be able to submit my data in the same way I receive it from the API.

You can use PrimaryKeyRelatedField :

Example from DRF Docs:

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

Your code would most likely be:

class ChildSerializer(serializers.ModelSerializer):
    parent = serializers.PrimaryKeyRelatedField(many=True)
    class Meta:
        model = Child
        fields = ('id', 'name', 'parent',)
        read_only_fields = ('id',)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM