Home > Software engineering >  Django can i only pass "id" in POST request, despite displaying nested fields?
Django can i only pass "id" in POST request, despite displaying nested fields?

Time:11-16

in my post requests to OrderProduct model, i want to only have to pass order.id and product.id and it works... untill i add a serializer to retrieve product.name. It might be because i didnt understand documentation about nested requests, but im unable to advance further into my project :(

[
    {
        "id": 2,
        "order": 1,
        "product": 1,        
    }
]

^ here's how it looks without nested serializer, and thats the data that i wanna have to input

[
    {
        "id": 2,
        "order": 1,
        "product": {
            "id": 1,
            "name": "gloomhaven",           
        },
        
    },

^ here's how it looks after i add an additional serializer. I pretty much want these nested fields to be read only, with me still being able to send simple post requests

here are my serializers

class OrderProductSerializer(serializers.ModelSerializer):   
    product = Product()
    class Meta:
        model = OrderProduct
        fields = [
            "id",
            "order",
            "product"]
class Product(serializers.ModelSerializer):    
    class Meta:
        model = Product
        fields = ( 
            "id",
            "name")

Is there any way for me to accomplish this? Thank you for trying to help!

CodePudding user response:

Just overwrite to_representation method of the serializer

def to_representation(self, instance):
    response = super().to_representation(instance)
    response['other_field'] = instance.id# also response['other_field'] = otherSerializer(instance.model)    
    return response

This can solve your problem

CodePudding user response:

I think you are missing many=True

class OrderProductSerializer(serializers.ModelSerializer):   
    product = Product(many=True)
    class Meta:
        model = OrderProduct
        fields = [
            "id",
            "order",
            "product"]
  • Related