我正在查看this question关于将特定方法链接到模型条目的结果,但不确定最终使用的解决方案是否优雅......
我希望从数据库中的模型条目中获得某种特定方法的指针。这是关于如何做到这一点的想法,但看起来很笨重:
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()
是否有更好或更常用的解决方案?比如将方法存储为数据库条目的一部分?谢谢:))
答案 0 :(得分:1)
你可以使用纯逻辑。你的方式实际上是最好的方式。但是,如果你的引用永远不会改变并且是预先定义的,那么你可以使用一个使用if,else和id的方法。
if instance.id = 1:
logic or method call here
else if instance.id = 2:
different logic or method call here
...
但是要意识到这意味着您的案例/逻辑引用是以这种方式预先定义的,并且永远不会改变。因此,如果您想要动态引用,那么您的解决方案可能是最好的方法。