json序列化序列化程序实例

时间:2019-08-09 02:37:50

标签: django-rest-framework

我想在POST之后返回一些有用的信息到我的api。我有

# views.py
from .serializers import FlagInstanceSerializer

SomeViewSet(viewsets.ModelViewSet):
...

    @action(detail=True, methods=['post'])
    def flag(self, request, pk=None):
        some_model = self.get_object()
        flag_instance = flaggit.utils.flag(some_model, user=request.user, ip=None, comment=None)
        serializer = FlagInstanceSerializer(data=flag_instance)
        serializer.is_valid()
        return Response(data=serializer.data)

模型

# models.py
class FlagInstance(models.Model):
    flag = models.ForeignKey(Flag, related_name='flags', on_delete=models.CASCADE)
    user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
    ip = models.GenericIPAddressField(blank=True, null=True)
    datetime = models.DateTimeField(auto_now_add=True)
    flag_type = models.PositiveIntegerField(choices=FLAG_TYPES, default=1)
    comment = models.TextField(blank=True, null=True)

    def __str__(self):
        return u'%s: %s' % (self.user, self.flag.content_object)

序列化器

# serializers.py
from flaggit.models import FlagInstance

class FlagInstanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlagInstance
        fields = '__all__'

rest docs显示以下健全性检查。

In [1]: from polls.serializers import FlagInstanceSerializer

In [2]: serializer = FlagInstanceSerializer()

In [3]: print(repr(serializer))
FlagInstanceSerializer():
    id = IntegerField(label='ID', read_only=True)
    ip = IPAddressField(allow_null=True, required=False)
    datetime = DateTimeField(read_only=True)
    flag_type = ChoiceField(choices=((1, 'Inappropriate'), (2, 'Move To Jobs'), (3, 'Move To Events'), (4, 'Move To Promotions')), required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
    comment = CharField(allow_blank=True, allow_null=True, required=False, style={'base_template': 'textarea.html'})                                                                                            
    flag = PrimaryKeyRelatedField(queryset=Flag.objects.all())
    user = PrimaryKeyRelatedField(allow_null=True, queryset=User.objects.all(), required=False)

api的响应为{}。我希望api以FlagInstance对象的json表示形式进行响应。

1 个答案:

答案 0 :(得分:0)

您实际上需要将实例“放入”序列化器中,以将值序列化为JSON。当前,您正在修改一个属性,该属性用于将数据反序列化为python对象。

将您的viewset方法更改为此,将data替换为instance

    @action(detail=True, methods=['post'])
    def flag(self, request, pk=None):
        some_model = self.get_object()
        flag_instance = flaggit.utils.flag(some_model, user=request.user, ip=None, comment=None)
        serializer = FlagInstanceSerializer(instance=flag_instance)
        return Response(data=serializer.data)