Django 和领域层
如何使用 django 组织我的域层?
我知道我可以编写自定义管理器来保存我的查询,但是如果我想要更灵活的东西(例如规范模式)怎么办?
是否有 Django 特有的域模式?
我目前正在设计一个使用 Django 的大型应用程序,我想知道如何正确完成域层。
How to organize my domain layer using django?
I know I can write custom managers to hold my queries but what if I want something more flexible like the specification pattern.
Is there any domain patterns that are unique to Django?
I am currently designing a large application that uses Django and I'd like to know how to do the domain layer right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题有点主观,但我的两点意见是:
MyModel.objects.create_complex(foo, bar)
my_instance.get_accumulated_interest()
。这些不应该保存模型,只更新一些字段然后返回。clean
方法中,或者作为特殊形式的clean
方法。如果它位于模型上,则可以更轻松地从系统的不同部分重用它。当我说“应该进入 X”时,我的意思是系统的这些部分应该调用您自己的模块,这些模块可能与 Django 完全分开。这可以使单独测试这些功能变得更容易。
编辑:
对于“规范模式”,我建议编写一个更高级别的模块来调用管理器方法来过滤对象。使用 Q 对象,您可以可以创建通用过滤器,您可以像这样使用:
编辑 II:
我突然想到:Python 允许非常通用的编程。类和函数是一等公民。考虑下面的例子:
你看到我刚才做了什么吗? :)
This question is a bit subjective, but here are my two cents:
MyModel.objects.create_complex(foo, bar)
my_instance.get_accumulated_interest()
. These should not save the model, only update some fields and then return.clean
methods on the model or asclean
methods in special forms. If it is on the model it can be reused from different parts of the system more easily.When I say "should go in X", I mean that these parts of the system should call into your own modules that may be separate from Django alltogether. This may make it easier to test these functions in isolation.
Edit:
For the "specification pattern" I would suggest writing a higher-level module that calls manager methods to filter objects. With Q objectsyou can create generic filters that you can use like this:
Edit II:
It just struck me: Python allows very generic programming. Classes and functions are first-class citizens. Consider the following example:
You see what I just did there? :)