Py学习  »  Django

使用django get_queryset()返回字典列表

Vikas Gautam • 5 年前 • 656 次点击  

我在尝试从数据库中获取和返回数据时遇到错误。

我在用 get_queryset() 正在返回queryset。我使用的命令是 data = MyModel.objects.filter(account_id=account_id) 但我错了 “BaseList”对象没有“items”属性 .

我想是因为我在数据库中的数据,我在数据库中有这种格式的数据,是因为结果有字典列表吗?

{
"result" : [ 
        {
            "savings" : 43.0548666420733,
            "count" : 18
        }, 
        {
            "savings" : 387.651510654053,
            "count" : 161
        }],
    }

模型.py

from mongoengine import Document, fields


class MyModel(Document):
    result = fields.DictField()

视图.py

class MyModelViewset(viewsets.ModelViewSet):

    renderer_classes = [renderers.JSONRenderer]
    serializer_class = MyModelSerializer

    def get_queryset(self):
        try:
            data = MyModel.objects.filter(account_id=self.kwargs['account_id'])
            return data
        except Exception as e:
            logger.exception(e)

序列化程序.py

class MyModelSerializer(serializers.DocumentSerializer):
class Meta:
    model = MyModel
    fields = '__all__

网址.py

url(r'^account/(?P<account_id>\w+)/myviews',MyModelViewset.as_view({'get':'list'}))
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52724
 
656 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Vikas Gautam
Reply   •   1 楼
Vikas Gautam    6 年前

因为我怀疑错误来自数据库。 我改了这个

    {
"result" : [ 
        {
            "savings" : 43.0548666420733,
            "count" : 18
        }, 
        {
            "savings" : 387.651510654053,
            "count" : 161
        }],
    }

为了这个

    {
"result" : {"data":[ 
        {
            "savings" : 43.0548666420733,
            "count" : 18
        }, 
        {
            "savings" : 387.651510654053,
            "count" : 161
        }]}
    }

现在一切都很好。 基本上, result 属于 array 我把它改成了 object