Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and domain driven design

I am confused about Domain Driven Design Approaches. From the sources on net I understood it is way of segregating your Domain Objects and Database Objects but I don't understand the difference between two.

For an example lets take the code of Polls example in django tutorial, there are two models Polls and Choice.

Are these domain level objects or database level objects?

Is there a need for DDD with an ORM?

If yes, can you provide a good situation where you need to use DDD approach with an ORM

For example, this is the model

class Polls(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

DDD approach code I have seen people writing

class PollService(object):
    def __init__(self, poll_repository):
        self.poll_respository = poll_respository

    def update(self, poll_id):
        poll = self.poll_respository.fetch_by_id(poll_id)
        poll.question += '?'
        self.poll_respository.update(poll)

#assume that the following code works?
class PollRepository():

    def __init__(self, db):
        self.db = db

    def update(self, poll):
        try:
            self.db.session().add(poll)
            self.db.session.commit()
        except Exception:
            self.db.session.rollback()

Is this a correct approach? I see a lot of redundant code here but people say that Polls is a domain level object and it should not directly talk to database?

Does DDD always comes with a DDD-reposiotry ? Why we need a DDD repository if we have an ORM

Another approach

views.py
def update_poll(poll_id):
    poll = models.Polls.objects.get(poll_id)
    poll.question += '?'
    poll.save()

What is wrong with this approach?

like image 760
Anubhav Agarwal Avatar asked Feb 04 '17 07:02

Anubhav Agarwal


People also ask

Is Django a DDD?

Some of the concepts of DDD are present in Django. Entities, Repositories, Aggregates, and Value Objects resemble the abstractions of ORM models, managers, or HTTP request objects. The code that is missing from Django might be the code specific to your business, and that is where DDD can help.

Is domain driven design still relevant?

Domain Driven Design (DDD) has recently gained additional popularity, as evidenced by new books, conference talks, and even complete conferences dedicated to it), and lots of trainings – including some by our very own colleagues here at INNOQ.

What is domain driven design good for?

Domain-Driven Design(DDD) is a collection of principles and patterns that help developers craft elegant object systems. Properly applied it can lead to software abstractions called domain models. These models encapsulate complex business logic, closing the gap between business reality and code.

What is domain driven design example?

An aggregate is a domain-driven design pattern. It's a cluster of domain objects (e.g. entity, value object), treated as one single unit. A car is a good example. It consists of wheels, lights and an engine.


3 Answers

Active Record Pattern

Django is tailored towards the use of the Active Record Pattern as described on this Django Design Philosophy page.

Your second example follows this pattern - the model itself has its properties, behaviour and data access contained within.

You can still use this pattern in a more DDD-like way, if you push more behaviour onto the model. e.g. in your example, a more effective use of the pattern would be to wrap the line

poll.question += '?'

in an intention revealing method on the poll object, so that the update_poll method is:

views.py
def update_poll(poll_id):
    poll = models.Polls.objects.get(poll_id)
    poll.add_question()
    poll.save()

This has the advantage of separating the business logic (pushed into the model) from the application flow logic (the update_poll method)

Although I'd suggest using a name that actually illustrates the intent or purpose of the method rather than just add_question.

But even if you do this, you are still using the Active Record pattern, not pure DDD.

You ask "Is there a need for DDD with ORM?"

DDD and an ORM are attempting to solve different problems. ORMs provide a convenient way of abstracting the set-like record-oriented world of databases in a more object oriented fashion.

DDD is an approach to assist with modelling complex real world situations in code.

Many DDD systems use ORMs to solve the infrastructure concerns of retrieving and persisting from the database (sometimes wrapping the ORM in a repository for a variety of reasons), but the DDD focus is on the domain models and how suitably they model the domain under consideration.

So - in your example, the benefits of DDD are difficult to see, as the business logic is so relatively simple.

I recommend reading the authoritive source on DDD - Domain Driven Design by Eric Evans for a language agnostic overview of the approach and the situations where it adds value.

Update

You ask:

Can you update me with one good example where using DDD with an ORM makes sense

and

If we use ORM I think there is no need for a DDD-repository

I think a better way to think about it is - when using an ORM, the ORM is the repository. You ask it for a model and it returns a model. That is the purpose of a repository. When people wrap it in a class called 'repository' it is usually because they want to do one of a few things:

  1. make it easier to inject a mock repository to simplify unit testing
  2. abstract the specific orm technology used to give flexibility to change the ORM later without having to touch the services or domain

This overview of the repository pattern provides another good writeup of the ddd repository pattern.

like image 192
Chris Simon Avatar answered Oct 19 '22 03:10

Chris Simon


Paul Hallett put it all together in his beautiful and complete article: https://phalt.github.io/post/django-api-domains

And the example here: https://github.com/phalt/django-api-domains

In brief:

Django’s style guide is old

The documentation, from the tutorials to the full docs, talk about a model-view-controller world in which Django renders HTML and delivers it to a web browser.

Something about this struck me as odd - I have worked with Django since 2012, and I only remember using it to render HTML once. Nearly all my time with Django, and all the time I have seen Django being talked about at conferences has been to provide an API (usually with Django REST Framework) to a frontend project. I would argue that this is actually the defacto standard for Django today. The documentation is out of date for the current popular use-cases. This is generally a trend I am seeing with Django - the project is trying to modernise how it is run and even how to handle async properly. Maybe it is time Django re-considered the design patterns it suggests for developers too?

Back to my immediate problem: in order to help the team organise their software better, I set out to find a good styleguide from the community. I read about Domain Driven Resign, the benefits of bounded contexts, and I found a nice styleguide by Hacksoft that we tried to use. This was great! The documentation here was very sound, and perfect for smaller projects or small companies.

But during our experimentation with it, we found it wasn’t fit for purpose for a few reasons. Namely, the fact that is encouraged business logic to live in the models. Django also recommends this and it is basically the active record pattern. In our experience with very large teams, keeping business logic tied to the models encouraged developers to fill up models.py with tonnes of code. This makes it very hard for developers to work on one file at the same time. Not to mention the fact that when a single file owns more than one problem in a domain (presentation, data, controller, etc) it tends to suck all other problems into the file too.

like image 22
adilnaimi Avatar answered Oct 19 '22 03:10

adilnaimi


If you need some examples regarding DDD and Django then this https://dry-python.org/static/slides/ddd-toolkit-2.html slides using dry python tools could be useful.

Also, check the example project https://github.com/dry-python/tutorials/tree/master/django/example

like image 35
auvipy Avatar answered Oct 19 '22 04:10

auvipy