Back
Feb 18, 2010

Business logic in models

Vladimir Sidorenko
Vladimir Sidorenko

In my recent project there was a lot of data business logic, so I had to organize this code somehow. In this article I'll describe a few hints on how to it.

Mixins

Simple business logic functions should in models or managers. When there's a lot of them, the can be split in mixins.

# logic.py

    class EventLogic(object):
        def start(self):
            if self.condition():
               # ...

    # models.py

    class Event(models.Model, EventLogic):
        name = models.CharField()
        # ...

Custom exceptions

For business logic errors you should declare custom exception classes. It's not fun to understand what this specific IntegrityError means.

Generic views

When all logic is in model and can throw, say, BusinessLogicException, we can write views like this:

from django.contrib import messages

    def event_action(requets, event_id, action):
        # event = get_object_or_404(...)
        try:
            getattr(event, action)(request.user)
        except BusinessLogicException, e:
            messages.warning(request, e.message)

        return redirect(request.POST.get('next') or event)

More thoughts

May 26, 2017Technology
Tutorial: Django User Registration and Authentication

In this beginners friends article I'll explain how to make authentication with Google account on your Django site and how to make authentication for you REST API.

Denis Untevskiy
Denis Untevskiy
May 09, 2018Technology
How to Generate PDF Files in Python with Xhtml2pdf, WeasyPrint or Unoconv

Programmatic generation of PDF files is a frequent task when developing applications that can export reports, bills, or questionnaires. In this article, we will consider three common tools for creating PDFs, including their installation and converting principles.

Vladimir Sidorenko
Vladimir Sidorenko
Jun 01, 2018Technology
Site search organization: basic concepts

Now it's time to get acquainted with Elasticsearch. This NoSQL database is used to store logs, analyze information and - most importantly - search.

Viktor Tyshchenko
Viktor Tyshchenko
Jun 25, 2011Technology
Ajax blocks in Django

Quite often we have to write paginated or filtered blocks of information on page. I created a decorator that would automate this process.

Vladimir Sidorenko
Vladimir Sidorenko