How can I map a django model to a python dataclass

Viewed 1329
1 Answers

Solution 1 (preferred way, support for custom datatypes, mapping both ways):

Check my answer here Using Python Dataclass in Django Models

Solution 2:

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

Example:

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

Notice:

  • This solution requires that Dataclass fields should be also defined in Model
  • I only tested this solution using string fields.
Related