gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:09:35 24 4
gpt4 key购买 nike

我有一个名为“电话”的通用模型:

(my_project/apps/phones/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/apps/clients/models.py)

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

phones = GenericRelation(Phone)

我还有一个用于“客户端”的序列化器:

(my_project/apps/clients/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 ),据我了解,我需要将自定义类放在同一个文件中,所以这是我的 client/serializers.py 的样子:

(my_project/apps/clients/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

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

最佳答案

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

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更新

电话 = PhoneObjectRelatedField(queryset=Phone.objects.all())

关于python - 如何提供正确的请求正文来序列化 Django 通用外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48780201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com