简体   繁体   English

空查询集的 Django rest 框架序列化程序数据

[英]Django rest framework serializer data for empty queryset

If there are no objects in a queryset, is there a way to send null values for all the attributes如果查询集中没有对象,有没有办法为所有属性发送 null 值

models.py模型.py

class ExampleModel(models.Model):
    key1 = models.CharField(max_length=100)
    key2 = models.CharField(max_length=100)
    key3 = models.CharField(max_length=100)

serializer.py序列化程序.py

class ExampleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ExampleModel
        fields = '__all__'

views.py视图.py

@api_view(['GET'])
def objects_list(request):
    if ExampleModel.objects.all():
        objects = ExampleModel.objects.all()
        serializer = ExampleModelSerializer(objects, many=True)
        return Response(serializer.data)
    else:
        return Response('No Objects')

Here in this case if there are no objects then is there a way to get a response like this instead of a string在这种情况下,如果没有对象,那么有没有办法获得这样的响应而不是字符串

[    
    {
        "id": null,
        "key1": null,
        "key2": null,
        "key3": null,
    }
]

Just an idea, but I think it will be easier to use a normal Serializer from django-rest-framework in this case instead of a ModelSerializer .只是一个想法,但我认为在这种情况下使用django-rest-framework中的普通Serializer器而不是ModelSerializer会更容易。

class TestSerializer(serializers.Serializer):
    key1 = serializers.CharField(max_length=100, allow_null=True, required=False)
    key2 = serializers.CharField(max_length=100, allow_null=True, required=False)
    key3 = serializers.CharField(max_length=100, allow_null=True, required=False)


class TestModelSerializer(serializers.ModelSerializer):
    """
    A model serializer would also work, you'd just have to
    do some of the manual work yourself for a few fields
    """
    id = serializers.UUIDField()
    created_at = serializers.DateTimeField()

    class Meta:
        model = ExampleModel
        fields = ('id', 'created_at', 'key1', 'key2', 'key3')


@api_view(['GET'])
def objects_list(request):
    if ExampleModel.objects.all():
        objects = ExampleModel.objects.all()
        serializer = ExampleModelSerializer(objects, many=True)
        return Response(serializer.data)
    else:
        initial = {'key1': None, 'key2': None, 'key3': None}
        serializer = TestSerializer(data=initial)
        serializer.is_valid(raise_exception=True)
        return Response(serializer.data)

Would return something like this in the response:会在响应中返回如下内容:

{
  "key1": null,
  "key2": null,
  "key3": null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM