0

我使用下面给出的 taskIdSerializer 创建数据的方法:

def to_representation(self, instance):
        result = super(taskIdSerializer, self).to_representation(instance)
        result = OrderedDict([(key, result[key]) for key in result if result['date']])
        return result

这个结果在我的函数中返回,如下所示:

[
    {
        "description": "asdsa",
        "priority_id": 3,
        "name": "tetst",
        "date": [
            {
                "dates": "20/09/2021 15:14:00",
                "id": 146
            },
            {
                "dates": "20/09/2021 15:14:00",
                "id": 145
            }
        ]
    },
    {}, // this is value add dict when date = []
    {}  // this is value add dict when date = []
]

我想删除 {} 对象,我想得到这样的返回数据:

[
        {
            "description": "asdsa",
            "priority_id": 3,
            "name": "tetst",
            "date": [
                {
                    "dates": "20/09/2021 15:14:00",
                    "id": 146
                },
                {
                    "dates": "20/09/2021 15:14:00",
                    "id": 145
                }
            ]
        }
    ]
4

2 回答 2

1

在我看来,您所拥有的不像 OrderedDict。OD 通常表示为元组对的列表。您正在显示字典列表。

如果您的列表总是有两个元素长,那么您可以说

result.pop()

从列表中删除最后一个元素。

你可以说得更紧一点:

if result[-1] == {}:
    result.pop()

但是,总的来说,我认为您需要回过头来更深入地了解您正在生成的输出。

更新:

我必须承认,我仍然看不到您获得的数据是如何来自 OrderedDict,至少不是来自 collections.OrderedDict。但是,无论如何,您有一个字典列表,并且您想摆脱空字典。所以,一些简单的事情:

result # from before
pared_result = [d for d in result if d != {}]

或者有些人可能会说以下内容更“Pythonic”:

pared_result = [d for d in result if not d]

如果列表的元素result总是dicts,那么上面两个是等价的。但是,如果元素可以不是字典,则上述两个将有所不同。

上述修改后的答案都使用了一种称为列表理解的强大形式。这是添加到您的实用腰带的绝佳工具。:)

于 2021-09-20T12:46:24.250 回答
-1

使用pop()函数删除。

于 2021-09-20T12:56:31.083 回答