从姜戈简史中获取睡觉历史 [英] Getting rest history from Django simple History

查看:23
本文介绍了从姜戈简史中获取睡觉历史的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Django-Simple-History(1.8.1)和DRF(3.5.3)。我想要一个包含每个元素历史记录的睡觉服务。让我们举个例子!

mods.py

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.IntegerField()
    history = HistoricalRecords()

    def __str__(self):
        return self.name

那么,seralizers.py必须是什么?我想要这样的东西:

[
    {
        "id": 1,
        "name": "Apple",
        "price": 8,
        "history": [
            {
                "history_id": 1,
                "id": 1,
                "name": "Apple",
                "price": 0,
                "history_date": "2016-11-22T08:02:08.739134Z",
                "history_type": "+",
                "history_user": 1
            },
            {
                "history_id": 2,
                "id": 1,
                "name": "Apple",
                "price": 10,
                "history_date": "2016-11-22T08:03:50.845634Z",
                "history_type": "~",
                "history_user": 1
            },
            {
                "history_id": 3,
                "id": 1,
                "name": "Apple",
                "price": 8,
                "history_date": "2016-11-22T08:03:58.243843Z",
                "history_type": "~",
                "history_user": 1
            }
        ]
    }
]

在找不到解的情况下,我终于自己找到了。但如果有人有更好的解决方案.

推荐答案

我知道已经一年了,但不管怎样,也许有人会觉得有用。以下是我的解决方案(在我看来容易得多):

新的序列化程序字段:

class HistoricalRecordField(serializers.ListField):
    child = serializers.DictField()

    def to_representation(self, data):
        return super().to_representation(data.values())

现在只需将其用作序列化程序中的a字段:

history = HistoricalRecordField(read_only=True)

这利用了DRF内置的listdict序列化程序,唯一的诀窍是向它传递正确的迭代量,这是通过调用简单历史模型管理器类上的.values()来完成的。

这篇关于从姜戈简史中获取睡觉历史的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆