0

I am working in a drf & react app . Where i need to show details of a foreign key field but when in POST method i need post only ID.But its not norking for nested serilizer. Giving an error from frontend named "Expected Dictonary but got int". output:

{
    "id": 1,
    "Hospital": {
        "id": 1,
        "User_Info": "bnsb@gmail.com",
        "Manager_Name": "Jalal Uddin",
        "Address": "Dhaka"
    },
    "FullName": "s",
    "Age": "s",

Models.py:

class Hospital(models.Model):
      User_Info = models.ForeignKey(User , on_delete=models.CASCADE)
      Manager_Name =  models.CharField(max_length= 40 , blank=True, null=True)
      Address = models.CharField(max_length=40 , blank=True, null=True)

class Patient(models.Model):
    Hospital = models.ForeignKey(Hospital , on_delete= models.CASCADE , default = 1) 
    FullName = models.CharField(max_length = 50 , blank = False , null = False , default = "")
    Age = models.CharField(max_length=12 , blank=True, null=True)

def __str__(self):
    return str(self.User_Info.Hospital_Name)

Serilizers.py:

class HospitalDetailsForPatientSerializer(serializers.ModelSerializer):
    User_Info =  CustomUserSerializer(read_only= True)
    class Meta:
        model = Hospital
        fields = "__all__"
        extra_kwargs = {"Address":{'read_only': True} ,"Manager_Name":{'read_only' : True}}

I got the expected output, Now I need to POST the only ID of Hospital Model when I save the patient but it's not working.

atik mahbub
  • 67
  • 2
  • 7
  • Does this answer your question? [DRF: Simple foreign key assignment with nested serializers?](https://stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers) – JPG Jul 07 '20 at 15:38

1 Answers1

0

I solved the problem by defining the to_representation method in the parent serializer. Now I can see the foreign key details in the 'GET' method but when I want to POST foreign it needs only ID. Serializers.py :

class HospitalDetailsForPatientSerializer(serializers.ModelSerializer):
      User_Info =  CustomUserSerializer()
      class Meta:
           model = Hospital
           fields = ['User_Info']

class PatientSerializer(serializers.ModelSerializer):
    class Meta:
         model = Patient
         fields = "__all__"

    def to_representation(self, instance):
        response = super().to_representation(instance)
        response['Hospital'] = HospitalDetailsForPatientSerializer(instance.Hospital).data
        return response
atik mahbub
  • 67
  • 2
  • 7