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
Nov 29, 2022Technology
React Performance Testing with Jest

One of the key requirements for modern UI is being performant. No matter how beautiful your app looks and what killer features it offers, it will frustrate your users if it clangs.

May 10, 2018Technology
How to Build a Cloud-Based Leads Management System for Universities

Lead management is an important part of the marketing strategy of every company of any size. Besides automating various business processes, privately-held organizations should consider implementing an IT solution that would help them manage their leads. So, how should you make a web-based leads management system for a University in order to significantly increase sales?

Aug 25, 2017Technology
How to Upload Files With Django

File upload works differently from simple form inputs, which can be somewhat troublesome for beginners. Here I'll show you how to handle uploads with ease.

Jun 14, 2017Technology
How to Deploy a Django Application on Heroku?

In this article I'll show you how to deploy Django with Celery and Postgres to Heroku.

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.

May 12, 2010Technology
Twitter API, OAuth and decorators

In my current project I had a task to use twitter API. Twitter uses OAuth for authentication, which is pretty dreary. To avoid fiddling with it all the time, I've moved authentication to decorator. If key is available - nothing happens, just view is launched as usual. It's convenient that there's no need for additional twitter settings in user profile. Code is in article.