我有一个名为followers
的方法字段。我在SerializerMethodField
:
followers = serializers.SerializerMethodField()
我想使用名为BaseUserSmallSerializer
的特定序列化程序格式化结果。我应该如何实现方法get_followers
来实现这一目标?
答案 0 :(得分:31)
试试这个;
followers = BaseUserSmallSerializer(source='get_followers', many=True)
或强>
您可以在methodfield中使用序列化程序;
def get_followers(self, obj):
followers_queryset = #get queryset of followers
return BaseUserSmallSerializer(followers_queryset, many=True).data
答案 1 :(得分:0)
如果您希望使用更通用的解决方案:
SerializerMethodNestedSerializer 与序列化器相同。 SerializerMethodField ,但将结果与传递的序列化器包装在一起并返回 dict
class SerializerMethodNestedSerializer(serializers.SerializerMethodField):
"""Returns nested serializer in serializer method field"""
def __init__(self, kls, kls_kwargs=None, **kwargs):
self.kls = kls
self.kls_kwargs = kls_kwargs or {}
super(SerializerMethodNestedSerializer, self).__init__(**kwargs)
def to_representation(self, value):
repr_value = super(SerializerMethodNestedSerializer, self).to_representation(value)
if repr_value is not None:
return self.kls(repr_value, **self.kls_kwargs).data
用法
class SomeSerializer(serializers.ModelSerializer):
payment_method = SerializerMethodNestedSerializer(kls=PaymentCardSerializer)
def get_payment_method(self, obj):
return PaymentCard.objects.filter(user=obj.user, active=True).first()
class Meta:
model = Profile
fields = ("payment_method",)
class PaymentCardSerializer(serializers.ModelSerializer):
class Meta:
fields = ('date_created', 'provider', 'external_id',)
model = PaymentCard
SerializerMethodNestedSerializer(kls=PaymentCardSerializer)
的预期输出
None or {'date_created': '2020-08-31', 'provider': 4, 'external_id': '123'}