【问题标题】:Django rest framework serialize a dictionaryDjango rest框架序列化字典
【发布时间】:2017-02-09 06:22:41
【问题描述】:

大家好,我正在使用 Django REST 框架,我想序列化我在查阅数据库时获得的字典对象

  def retrieve(self, request, project_name=None):
    try:
      opc = {'name_proj' : project_name }
      alldata = connect_database(opc)
    except KeyError:
        return Response(status=status.HTTP_404_NOT_FOUND)
    except ValueError:
        return Response(status=status.HTTP_400_BAD_REQUEST)
    serializer = serializers.cpuProjectsSerializer(instance=alldata, many=True)
    return Response(serializer.data) 

当我调用connect_database(opc) 函数时,我会查询数据库并返回所有行。

之后创建一个字典 obj,我在 alldata 返回,所以我用字典调用我的序列化程序方法。

我的字典对象是这样的

{names:['example'], example:{jobs_running:[[], [],[] ]}, {jobs_pending:[[],[],[]] }}

真实数据是这样的

{'names': [u'ad'], u'ad': {
'jobs_running': [[1459861201000, 0L], [1459864801000, 0L], [1459868401000, 0L], [1459872001000, 0L], [1459875601000, 0L], [1459879201000, 0L], [1459882801000, 0L], [1459886401000, 0L]], 
'jobs_pending': [[1459861201000, 0L], [1459864801000, 0L], [1459868401000, 0L], [1459872001000, 0L], [1459875601000, 0L], [1459879201000, 0L], [1459882801000, 0L], [1459886401000, 0L]] }
}

我的问题是我不知道如何创建序列化程序文件。

我试试这个,返回一个类似字符串的名称,jobs_running 和 jobs_pendding 就像字典一样

class cpuProjectsSerializer(serializers.Serializer):
  project = serializers.CharField(max_length=256)
  jobs_running = serializers.DictField()
  jobs_pending = serializers.DictField()


  def create(self, validated_data):
    """
    Create and return a new `cpuProjects` instance, given the validated data.
    """
    return cpuProjects.objects.create(**validated_data)

  def update(self, instance, validated_data):
    """
    Update and return an existing `cpuProjects` instance, given the validated data.
    """
    instance.project = validated_data.get('names', instance.project)
    instance.save()
    return instance

但我收到此错误

The serializer field might be named incorrectly and not match any attribute or key on the `tuple` instance.
Original exception text was: 'tuple' object has no attribute 'project'. 

知道如何返回这些数据

提前致谢!

【问题讨论】:

  • {names:[], {jobs_running:[[], [],[] ]}, {jobs_pending:[[],[],[]] }} 不是有效的dict。如果您犯了错误,请更新答案。
  • 谢谢@vishes_shell 我更正了字典!
  • @vishes_shell 我期待类似highcharts.com/samples/data/…?
  • 对不起,0Lstr 对象?
  • 在我的例子中是一个 int @vishes_shell

标签: python django python-2.7 django-rest-framework


【解决方案1】:

问题是你的instanceTuple[ProjectModel, bool] 而不是Project 这就是为什么你会得到错误。实现应该是这样的

from typing import Tuple

def update(self, instance: Tuple[ProjectModel, bool] , validated_data):
    instance[0].project = validated_data.get('names', instance.project)
    instance[0].save()
    return instance

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2020-03-22
    • 2015-10-29
    相关资源
    最近更新 更多