如何将Django模型映射到python数据类 [英] How can I map a django model to a python dataclass

查看:57
本文介绍了如何将Django模型映射到python数据类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去在github中有一个项目,允许您将django模型映射到python数据类,但是现在不复存在了.您仍然可以使用退回的机器对其进行检查:

There used to be a project in github that allowed you to map django models to python dataclasses, but it's gone now. You can still check it using the way back machine:

https://web.archive.org/web/20201111163327/https://github.com/proofit404/mappers https://web.archive.org/web/20201101163715/https://proofit404.github.io/mappers/

我正在尝试寻找另一种将Django模型映射到python数据类的方法,但是我似乎找不到任何类似的项目

I'm trying to find another way to map django models to python dataclasses, but I can't seem to find any similar projects

推荐答案

解决方案1:

在这里检查我的答案在Django模型中使用Python数据类

可以使用此处实现的装饰器来完成:

It can be done using decorator implemented right here:

from django.db import models
from dataclasses import dataclass

# you can copy this decorator and use it or implement your own
def with_dataclass_mapper(dataclass):
    def wrapper(cls):
        def mapper(self):
            dataclass_kwargs = {}
            for field in dataclass.__dataclass_fields__:
                dataclass_kwargs[str(field)] = getattr(self, str(field))
            return dataclass(**dataclass_kwargs)
        # add 'map' method to class
        setattr(cls, 'map', mapper)
        return cls
    return wrapper

示例:

@dataclass
class MyDataclass:
    field1: str
    field2: str

@with_dataclass_mapper(MyDataclass)
class MyModel(models.Model):
    field1 = models.CharField(default="", max_length=255)
    field2 = models.CharField(default="", max_length=255)

modelInstance = MyModel(field1="foo", field2="bar")
myDataclassInstance = modelInstance.map()

注意:

  • 此解决方案要求还应在模型中定义数据类字段
  • 我仅使用字符串字段测试了此解决方案.
  • 这篇关于如何将Django模型映射到python数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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