【问题标题】:Post Foreign Key As Id but show Foreign Key Details in GET method将外键作为 ID 发布,但在 GET 方法中显示外键详细信息
【发布时间】:2020-07-08 17:00:30
【问题描述】:

我正在使用 drf & react 应用程序。我需要显示外键字段的详细信息,但在 POST 方法中我只需要发布 ID。但它不适用于嵌套序列化程序。从名为“预期字典但得到 int”的前端给出错误。 输出:

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

模型.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}}

我得到了预期的输出,现在我需要在保存患者时发布医院模型的唯一 ID,但它不起作用。

【问题讨论】:

标签: django serialization django-rest-framework


【解决方案1】:

我通过在父序列化程序中定义 to_representation 方法解决了这个问题。现在我可以在“GET”方法中看到外键详细信息,但是当我想发布外键时,它只需要 ID。 序列化器.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多