简体   繁体   中英

Django Rest Framework POST and PUT Foreign Key ModelSerializer

I have a problem with a model serializer. My models

class ItemState(models.Model):
"""Status for a item"""
name = models.CharField(max_length=255, null=True, blank=True)

class Item(models.Model):
    title = models.CharField(max_length=255)
    status = models.ForeignKey(ItemState, on_delete=models.CASCADE)

My serializer:

class ItemStateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemState
        fields = '__all__'


class ItemSerializer(serializers.ModelSerializer):
    status = ItemStateSerializer(read_only=True)
    class Meta:
        model = Item
        fields = '__all__'

And my viewset

class ItemViewSet(viewsets.ModelViewSet):
    """ Item view set """
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = (IsOwnerOrAdmin, )

My question is, how can i do a put or post without create a status object? I wanna replace this

HTTP PUT 
{
   "title": "example",
   "status": {
       "id": 1,
       "name": "hello"
   }
}

by this

HTTP PUT 
{
   "title": "example",
   "status": 1
}

Thanks community!

Do you want to keep the other class or can you get rid of it all together? It seems simpler to do:

class Item(models.Model):
    title = models.CharField(max_length=255)
    status = models.CharField(max_length=255)  # or you can change to int if you want

You can use two serializer fields for the same model field - one for details, and the other default with the id ( see this answer ). So in your case, your serializer can be defined as:

class ItemSerializer(serializers.ModelSerializer):
    status_detail = ItemStateSerializer(source='status', read_only=True)

    class Meta:
        model = Item
        fields = '__all__'

Now your PUT requests will be like you want:

HTTP PUT 
{
   "title": "example",
   "status": 1
}

but when you GET an Item , it will have ItemState details in the status_detail field:

HTTP GET
{
   "title": "example",
   "status": 1
   "status_detail": {
       "id": 1,
       "name": "hello"
   }
}

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