user2741831
user2741831

Reputation: 2398

Should buisness logîc be enforced in django python or in sql?

I am writing a rest backend for a project. Heres a basic example of the kind of problems I'm trying to solve. These students have tests with grades and each student has a column current_average_grade.
Everytime a test is stored, this average_grade_should be updated (using all existing tests).
So the question is, should this be calculated and stored with within the post view of django (get all grades from db and then do the calculation) or with an sql trigger and only use django to convert json to sql.
The advantage of using sql for this, is of course it should theoretically be much faster and you also get concurrency for free.
The disadvantage is that since I am now programming sql, I have yet another codebase to manage and it might even create problems with django.
So whats the ideal solution here? How do I enforce buisness logic in an elegant way?

Upvotes: 1

Views: 38

Answers (1)

Astik Anand
Astik Anand

Reputation: 13047

I think dealing it in Django views will be a better idea. In this way you can control the business logic in a better way and also you don't need to manage the database extensively.

And for handling concurrency Django provides a beautiful way in the form of select_for_update().

Handling Concurrency in Django

To acquire a lock on a resource we use a database lock. And in Django we use select_for_update() for database lock.

Example Code

from django.db import transaction

entries = Entry.objects.select_for_update().filter(author=request.user)
with transaction.atomic():
    for entry in entries:
        # action on each entry in thread-safe way

Upvotes: 3

Related Questions