Associate a function with a model record

I looked at the result of this question about binding a specific method to a model record, but I'm not sure if the solution used at the end is elegant ...

I want to have some kind of pointer to a specific method from the model record in the database. This is my idea on how to do this, but it seems to be inconvenient:

class Results(models.Model):
    result_ref = models.CharField(...)
    result_name = models.CharField(...)
    result_unit = models.CharField(...)

def result_1_method():
    return "My custom result for entry 1"

...

>>> results_map = {1: result_1_method, 2: result_2_method, ...}
>>> required_result = Results.objects.get(results_ref='XAY')
>>> required_result_method = results_map[required_result.id]
>>> result = required_result_method()

Is there a better or more commonly used solution? For example, how to store a method as part of a db record, for example? Thank:)

+4
source share
1 answer

. . , , , if, else .

if instance.id = 1:
    logic or method call here
else if instance.id = 2:
    different logic or method call here
...

, , / . , , , , .

0

Source: https://habr.com/ru/post/1681883/


All Articles