9
9
95506682020-08-02 14:10:28
Django
9550668, 2020-08-02 14:10:28

How to properly structure a Model in Django?

Hello everyone once again.

I read the documentation on the Models, studied everything, but there were questions. I hope you can advise.

Abstract situation:
1. There is a Model with several fields.
2. I need to write a number of internal functions for the model, so that the code would be more understandable, structured in more detail and the main load on working with the model fell not on the CWB, but on the internal functions of the model.

Actually, a question:
1. There is a function in model on delivery of the partial information (several fields of record).

#к примеру, простая функция внутри модели:
def return_user_age(self, user):
   ...
   return user.age


How can I call the given function from CWB without creating a new model variable?
That is, ideally, I would like to have a solution, for example, this:
print(Users.return_user_age(id=3))
where Users is the name of the model from the models.py file, id is the id of the user whose age I would like to get.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2020-08-02
@9550668

If based on the option in the question, then so:

@classmethod
def return_user_age(cls, user_id):
   user = cls.objects.get(id=user_id)
   return user.age

You can also write a manager for the model and resolve it through it. You can also do @property and you can just use model methods, the option depends on how you use all this stuff in the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question