Back
Feb 18, 2010

Business logic in models

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)

Subscribe for the news and updates

More thoughts
Aug 18, 2022Technology
5 Best Practices of RESTful API Design to Keep Your Users Happy

Dive into our guide to RESTful API best practices

Jul 27, 2022Technology
Forge Viewer: Our Experience with an Unusual Project

Once we received an interesting task from a client. They needed to allow their users to upload a 3D model of the building and show it in a timelapse video from the construction site.

Jul 13, 2022Technology
Prosemirror: Render node as react component

In this article I’m going to show how to declare custom prosemirror node, how to render it with toDom method and how improve that with custom NodeView using React component.

Jan 28, 2017Technology
Creating a site preview like in slack (using aiohttp)

In this article we will write a small library for pulling metadata and creating a preview for a site just like Slack does.

Jan 22, 2017Technology
Django vs Rails Performance

This article is aimed for beginners, who are trying to choose between Ruby on Rails and Django. Let’s see which is fastest and why.

Jan 12, 2017Technology
Making Custom Report Tables Using AngularJS and Django

In this article I will tell you how to create an interactive interface with a widely customized visual look and different filtering to view reports.