简而言之,序列化器:
class ReleaseComponentContactSerializer(StrictSerializerMixin, serializers.ModelSerializer):
component = serializers.SlugRelatedField(source='release_component', slug_field='name',
queryset=ReleaseComponent.objects.all())
role = serializers.SlugRelatedField(source='contact_role', slug_field='name',
read_only=False, queryset=ContactRole.objects.all())
contact = ContactField()
def to_representation(self, instance):
...........................
# I hope return one dict or multiple dict, for first instance it return dict1, for second one it return dict2, dict3
return ..............
class Meta:
model = RoleContact
fields = ('id', 'component', 'role', contact)
我希望结果类似于 dict1、dict2、dict3,而不是 dict1、[dict2、dict3]。是否可以?我想这就是我想要的。
最初的问题是我有三个模型,
class ReleaseComponent(models.Model):
.................
global_component = models.ForeignKey(GlobalComponent)
name = models.CharField(max_length=100)
contacts = models.ManyToManyField(Contact, through='contact.RoleContact', blank=True)
class RoleContact(models.Model):
contact_role = models.ForeignKey(ContactRole, related_name='role_contacts',
on_delete=models.PROTECT)
contact = models.ForeignKey(Contact, related_name='role_contacts',
on_delete=models.PROTECT)
global_component = models.ForeignKey('component.GlobalComponent', blank=True, null=True,
related_name='role_contacts')
release_component = models.ForeignKey('component.ReleaseComponent', blank=True, null=True,
related_name='role_contacts')
class GlobalComponent(models.Model):
"""Record generic component"""
.................................
contacts = models.ManyToManyField(Contact, through='contact.RoleContact', blank=True)
如果ReleaseComponent没有联系人,它将使用其GlobalComponent的联系人。所以一个RoleContact对象可能连接多个Release组件,因为1个RoleContact -> 1个GlobalComponent -> 多个ReleaseComponent。如果ReleaseComponent有一个联系人,并且这个联系人不与GlobalComponent共享,那么它必须是一个RoleContact -> 一个ReleaseComponent。一般来说,通过选择查询集,一个RoleContact -> 一个或多个ReleaseComponent。
希望输出格式保持一致。输出中,每一项对应一个ReleaseComponent的一个RoleContact信息。即使对于多个 ReleaseComponent 对象的 RoleContact 对象也是如此。我可以在 to_representation 中生成多个字典,但在最终输出中,这个多个字典将在一个列表中,例如
[dict2, dict3, dict4]
是否有可能将它们从最终输出的列表中剔除?成为以下组织的一部分:
字典1,字典2,字典3,字典4,字典5,......?
谢谢。
最佳答案
您可以在调用 serializer.data
后在 View 中执行此操作,以根据您的要求修改序列化数据。
您需要执行以下操作:
serialized_data = my_serializer.data # original serialized data
return_data = [] # final response which will be returned
for item in serialized_data:
if isinstance(item, list): # check if a list inside serialized data
return_data += item # add the elements of the list to 'return_data' list
else:
return_data.append(item) # Otherwise just append the item to 'return_data' list
return_data
包含最终所需的响应。
关于python - 序列化器的 to_representation 能否在 DRF 3 中生成多个输出项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32324117/