Despite it is very popular question and already has a lot of answers, I don't really get it. I understand that putting tons of logic in views is not a good idea, so in my projects I create files like utils
, logic
, helpers
. But the problem is that I don't know where should I call those "logical" functions? Should I make them as a property or method of model instance, or should I call it in a view passing model instance as an argument? For example in my current pet-project I have Question
and Answer
models. Question
has is_solved
Boolean (default=False
) field which means if the question is solved or not, and Answer
has is_solving
Boolean field (default=False
) as well and if True, it means that the answer helped to solve an issue. I have a function in logic
file which handles it. Here is the code:
def vote_answer_solving(answer: Answer, related_question: Question):
if answer.is_solving:
answer.is_solving = False
related_question.is_solved = False
else:
if related_question.question_answers.filter(is_solving=True).exists():
is_solving_answer = related_question.question_answers.get(is_solving=True)
is_solving_answer.is_solving = False
is_solving_answer.save()
answer.is_solving = True
related_question.is_solved = True
related_question.save()
answer.save()
I call it in a view, where user requests the endpoint and the logic is handled by the function. I don't really know, maybe I should place the logic in models save
method, so when it gets an answer with is_solving=True
, related question status is_solved=False
changes to True
.
This was just the example of my general misunderstanding of how to make my code cleaner, especially when I should place logic in similar situation to views (call the separeted function in there) or handle it on the level of model managers or save
method.
I do really hope if someone helps me someway by answering the question or recommending some books, articles related to the issue to read where I can find the appropriate solution. Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire