我想要 GET 上的完整相关模型,并在 CREATE、UPDATE 和 DELETE 上使用 id。 我尝试使用 to_representation。 所以我想创建一个名为 users 的字典数组,它应该显示完整的用户。
但是当我在对象中添加字典时,我收到错误“unhashable type: 'ReturnDict'”,如果我通过直接写入数组来为单个用户执行此操作,则效果很好。
class CompanySerializer(serializers.ModelSerializer):
#users = UserSerializer(many=True)
created_at = serializers.DateTimeField()
updated_at = serializers.DateTimeField()
class Meta:
model = Company
fields = ['id', 'name', 'street', 'city', 'postal_code', 'state', 'company_form', 'users', 'created_at', 'updated_at']
def to_representation(self, instance):
representation = super(CompanySerializer, self).to_representation(instance)
representation['company_form'] = CompanyFormSerializer(instance.company_form).data
representation['users'] = []
for entry in instance.users.all():
user = {UserSerializer(entry).data}
representation['users'].extend(user)
return representation
最佳答案
无需手动执行此操作,您可以将序列化器添加到序列化器中,例如:
class CompanySerializer(serializers.ModelSerializer):
<b>users = UserSerializer(read_only=True, many=True)
company_form = CompanyFormSerializer()</b>
created_at = serializers.DateTimeField()
updated_at = serializers.DateTimeField()
class Meta:
model = Company
fields = ['id', 'name', 'street', 'city', 'postal_code', 'state', 'company_form', 'users', 'created_at', 'updated_at']
有关详细信息,请参阅Dealing with nested objects section of the Django REST Framework documentation .
您的 to_representation
模型有两个部分错误:
- 您将
.data
的结果包装在一个集合中,但正如您发现的那样,字典不能放入字典中,因为集合是可变的;和 - 您应该在此处使用
.append(..)
而不是.extend(..)
。
def to_representation(self, instance):
representation = super(CompanySerializer, self).to_representation(instance)
representation['company_form'] = CompanyFormSerializer(instance.company_form).data
representation['users'] = []
for entry in instance.users.all():
user = <b>UserSerializer(entry).data</b>
representation['users']<b>.append(</b>user<b>)</b>
return representation
但是话虽这么说,在我看来,旨在自己做到这一点的软件设计是糟糕的。 Django 有很多工具可以通过 URI 等正确处理关系。
关于python - 如何更改 Django Rest Framework 中多对多相关对象的表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57458468/