如何提供正确的请求体来序列化Django通用外键?

时间:2018-02-14 05:24:59

标签: python django django-rest-framework jwt postman

我有一个名为' Phone':

的通用模型
  

(MY_PROJECT /应用/电话/ models.py)

class Phone(Model):
    owner_name = CharField(max_length=50)
    number = CharField(max_length=20)

    content_type = ForeignKey(ContentType, on_delete=CASCADE)
    object_id = PositiveIntegerField()
    phone_object = GenericForeignKey('content_type', 'object_id')

我还有一个名为' Client':

的模型
  

(MY_PROJECT /应用/客户端/ models.py)

class Client(Model):
    employee = ForeignKey(Employee, on_delete=CASCADE)
    title = CharField(max_length=50)

    phones = GenericRelation(Phone)

我还有一个用于'客户端':

的序列化程序
  

(MY_PROJECT /应用/客户端/ serializers.py)

class ClientSerializer(ModelSerializer):
    id = IntegerField(read_only=True)
    employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True)
    title = CharField(required=True)

我遵循drf-documenation(http://www.django-rest-framework.org/api-guide/relations/#generic-relationships),据我所知,我需要将自定义类放在同一个文件中,所以这就是我的clients / serializers.py的样子:

  

(MY_PROJECT /应用/客户端/ serializers.py)

class ClientSerializer(ModelSerializer):
    id = IntegerField(read_only=True)
    employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True)
    title = CharField(required=True)

class PhoneObjectRelatedField(RelatedField):
    def to_representation(self, value):
        if isinstance(value, Client):
            serializer = ClientSerializer(value)
        else:
            raise Exception('Unexpected type of phone_object')
        return serializer.data

对于我使用PostMan的请求,所以这是我创建带有电话号码的新客户的请求: enter image description here

但它没有做任何事,新客户可以成功创建,但他们只是不包含任何电话号码,请帮忙!

1 个答案:

答案 0 :(得分:2)

您可以将相关字段添加到序列化程序字段

class ClientSerializer(ModelSerializer):
    id = IntegerField(read_only=True)
    employee_id = PrimaryKeyRelatedField(queryset=Employee.objects.all(), source='employee', required=True)
    title = CharField(required=True)
    phone = PhoneObjectRelatedField()

由@ Madi7

更新

phone = PhoneObjectRelatedField(queryset=Phone.objects.all())