V
V
Vladimir2019-07-10 11:35:40
Django
Vladimir, 2019-07-10 11:35:40

How to properly organize code in Django?

Hello! The question is about the nuances of following the SOLID principles in Django.
There is a model (schematically) with a method

class Product(models.Model):
    name = models.CharField()
    type = models.CharField(choices=PRODUCT_CHOICES)
    
    def process_new_order(self, *args, **kwargs):
        if self.type == 'type one':
            """ do order """
        if self.type == 'type two':
            """ do another order """

In general, everything is cool, everything looks great in forms and views, but the following is true:
- By the principle of open / closed, we should avoid type checking.
That is, it would be logical to divide the model into two proxy models and predefine each method, but then in forms and views you need to how to determine the desired model class. Or maybe you need to proxy other models? or something different.
What do you think is the right way to organize this type of code?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2019-07-13
@FonVald

In essence, you have a "product type" business entity, each object of which implements its own way of doing "do order". Perhaps you should make a ProductType model and have a process_new_order(order: Product) method. Or perhaps it will be enough to make not a django model, but just a class in python, using the Strategy pattern.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question