【问题标题】:How can I map a django model to a python dataclass如何将 django 模型映射到 python 数据类
【发布时间】:2021-01-19 23:11:05
【问题描述】:

以前在 github 中有一个项目可以让您将 django 模型映射到 python 数据类,但现在已经不存在了。您仍然可以使用回程机检查它:

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

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

【问题讨论】:

    标签: python django django-models python-dataclasses


    【解决方案1】:

    方案一(首选方式,支持自定义数据类型,双向映射):

    在这里查看我的答案 Using Python Dataclass in Django Models

    解决方案 2:

    可以使用这里实现的装饰器来完成:

    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()
    

    注意:

    • 此解决方案要求 Dataclass 字段也应在 Model 中定义
    • 我只使用字符串字段测试了这个解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2012-02-25
      • 2018-10-22
      • 2018-06-19
      相关资源
      最近更新 更多