我要添加状态并将序列化器的输出放入DATA:
我的模特:
class UserDetails(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
user_group_id = models.ForeignKey(UserGroup, on_delete=models.CASCADE)
admin_photo = models.ImageField(upload_to='user_image',blank=True)
我的序列化器:
class UserDetailSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(many=False)
user_group_id = serializers.StringRelatedField(many=False)
class Meta:
model = UserDetails
fields = [
'user',
'user_group_id',
'admin_photo',
]
depth = 1
def to_representation(self, instance):
data = super(UserDetailSerializer, self).to_representation(instance)
return {
'STATUS' : 'SUCCESS',
'DATA' : data
}
我得到的答复是:
[
{
"DATA": {
"user": "user1",
"user_group_id": "Super Admin",
"admin_photo": "http://www.someurl.com/media/22-black-wallpaper.jpg"
},
"STATUS": "SUCCESS"
},
{
"DATA": {
"user": "user2",
"user_group_id": "Admin",
"admin_photo": "http://www.someurl.com/media/fox.jpg"
},
"STATUS": "SUCCESS"
}
]
但是我想要这样的响应,状态是基本文本,并且我想将Class meta的结果放入DATA
{
"STATUS": "SUCCESS",
"DATA": [
{
"user": "user1",
"user_group_id": "Super Admin",
"admin_photo": "http://www.someurl.com/media/22-black-
wallpaper.jpg"
},
{
"user": "user2",
"user_group_id": "Admin",
"admin_photo": "http://www.someurl.com/media/fox.jpg"
}
]
}
已编辑 仅使用listapiview进行查看,并使用序列化程序类:
class UserListView(generics.ListAPIView):
lookup_vield = 'id'
serializer_class = UserDetailSerializer
def get_queryset(self):
return UserDetails.objects.all()
答案 0 :(得分:1)
您无法在序列化程序级别执行此操作,但是可以通过覆盖 module PaymentGateway
class StripeClient
def lookup_customer(identifier: )
handle_client_error do
@lookup_customer ||= Stripe::Customer.retreive(identifier)
end
end
end
end
的 list(...)
方法在视图级别执行此操作
第1步。从 UserListView
序列化器中删除 to_representation
方法
第2步。将 UserDetailSerializer
的查看方法覆盖为
list()