跨越不同模型的 Django 方法的结构
我有两个模型(比如 A 和 B),它们是独立的并且具有独立的方法。我想添加一些在两种模型上运行的方法。
例如,addX() 将从模型 A 和 B 中创建一个对象。
在这种情况下构建代码的最佳方法是什么?该方法属于任何模型的方法是没有意义的。为这种“抽象”模型编写服务的标准是什么?
I have two models (say A and B) which are independent and have independent methods. I want to add some methods that operate on both models.
For example, addX() will create an object from both models A and B.
What's the best way to structure the code in this situation? It doesn't make sense that the method belongs to any of the models' methods. Is the standard to write a service for this kind of 'abstract' model?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定我完全理解你的问题。您是在问公共方法应该放在哪里,还是在问如何调用一个方法来作用于两个类?
如果您只需要通用方法,那么我将拥有一个抽象父模型,两个模型都可以子类化:
抽象元选项告诉 Django 不要为 ParentModel 创建任何实际的数据库表。它只是保存方法。
查看更多详细信息:http://docs.djangoproject。 com/en/dev/topics/db/models/#id6
I am not sure I fully understand your question. Are you asking about where to put the common methods or are you asking about how to call one method to act on two classes?
If you just need to have common methods, then I would have an abstract parent model that both models subclass:
the abstract meta option tells Django to not create any actual db tables for ParentModel. It is just there to hold the methods.
Check this out for further details: http://docs.djangoproject.com/en/dev/topics/db/models/#id6