Search code examples
pythondomain-driven-design

Persist POJOs in Python using a DDD approach


I'm trying to create a Flask application with DDD patterns.

One of the core principles of DDD is to separate the domain from the persistence (infrastructure). I have defined my domain models in a module, and am going to create a repository in the infrastructure module.

However, i can't seem to find any information as to how to persist POJOs in Python. I have looked at sqlalchemy, but with sqlalchemy you create persistence models. Creating domain models as persistence models is an anti pattern in DDD.

What persistence options are available for a use case like this? More specifically, what persistence options can i use to persist models defined as POJOs?


Solution

  • You can choose from a few strategies for this case. In many cases, it's not a problem that DTO for your aggregate is DB Model. If you want separation you can create an interface for this DTO and implement it in the repository as a model.

    class User:
        id: int
        name: Text
    
    class PlainUser(User):
        def __init__(self, name):
            self.id = autogenerate_id()
            self.name = name
    
    class DBUser(db.Model, User):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(100), nullable=False)
    

    Another strategy is to map sqlalchemy tables on POPO (btw. In Java you have POJO, Plain Old Java Object. In python you have POPO, Plain Old Python Object). So you declare table and use mappers instead of declarative mode. The third option is to use a library for mapping DB Model to POPO like dry-python/mappers. Also if you want to separate DDD components you need to think about separate migrations. To answer more deeply on this question (and another on StackOverflow) I wrote this post Persistency of DDD aggregate. Hope it will be helpful to you with other obstacles with DDD components.