在Djang®中存储与模型相关的重复代码的位置?

时间:2017-02-25 08:27:57

标签: django django-models architecture

我正在寻找一种在Django中管理不属于模型逻辑的重复模型相关代码的正确方法。

请记住:

  1. “评论”是一个可重复使用的应用程序,可以在其他项目中使用
  2. “评论”示例它只是问题的一个例子
  3. 示例:

    class Comments(models.model):
        ### model stuff ###
    

    线程评论渲染是一项昂贵的操作,因此我希望将它们作为HTML存储在缓存中。

    我们必须处理的重复代码:

    def get_comments_html(target_object):
        ## check cache
        ## is there is no cached copy, then build HTML and store to the cache
    

    我认为注释模型缓存逻辑与注释本身无关,应该放在其他任何地方。

    解决问题的方法:

    我认为以下是解决此问题的三种方法:

    1. 所有此类功能存储到模型使用者类中:

      class ModelConsumer(object):
          # here we can place repetitive code for all models (of just pass)
      
      class CommentsConsumer(ModelConsumer):
          model = Comments
      
          def get_comments_html(self, target_object): 
              # check for cahce
              comments = self.model.object.filter(target=target_object)
              # render HTML and store to cache
      
    2. 将这些逻辑独立存储为comment_app / utils.py

    3. 中的普通函数
    4. 为每个问题创建独立的类(f.e. CommentCacheManager等)
    5. 处理不属于模型逻辑的模型相关代码的最佳解决方案是什么?

      这个问题致力于寻找一种不会在未来导致产品限制的架构概念。

1 个答案:

答案 0 :(得分:0)

如果重复代码仅用于缓存HTML片段,则可以使用Django's template caching

但是,如果缓存逻辑不是微不足道的话可能会有麻烦。 get_comments_html似乎始终在注释的QuerySet上运行。您可以在模型中添加custom QuerySet,而不是将此代码放在管理器中,这样您就可以像这样使用缓存逻辑:

comments_html = Comment.objects.filter(target=target_object).get_comments_html()
相关问题