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

Mar 03, 2017Technology
Flask vs Django. Which Is Better for Your Web App?

There are two most popular web frameworks in Python. There is the Django with lots of intelligent defaults and the Flask micro framework with complete freedom in the choice of modules. Let’s see, what django vs flask is in 2017.

Denis Untevskiy
Denis Untevskiy
Oct 22, 2016Technology
Solr Sharding

When dealing with one of our projects (LookSMI media monitoring platform) we have to handle the huge volume of data – and its quantity is constantly growing. At the same time, we must run quick searches with smart rules. In this article I'll explain how we have achieved required performance.

Rostyslav Stekh
Rostyslav Stekh
Mar 07, 2017Technology
How Do You Use MongoDB With Python?

There are many ways to interact with MongoDB using Python. In this article we'll compare them and will help you make a decision.

Vlada Oliinyk
Vlada Oliinyk
Jan 09, 2017Technology
How to Use GraphQL with Django

GraphQL is a very powerful library, which is not difficult to understand. GraphQL will help to write simple and clear REST API to suit every taste and meet any requirements.

Rostyslav Stekh
Rostyslav Stekh