Django - 模型类接口?
我选择了一些与各种 Web API 交互的模型。我需要确保每个模型都有特定的方法。使用 PHP,我创建了一个类接口,以确保我的模型具有完成其工作所需的方法,但 Python 接口似乎不适用于 Django 模型。
我假设执行此操作的方法是创建一个扩展 model.Model 的基类,它定义了我需要的方法,并且如果需要,我可以在每个 API 模型中覆盖它们。在同步数据库时,如果 Django 不选择“基”类,我如何才能做到这一点?这是正确的做法吗?
I have a selection of models which interact with various web APIs. I need to ensure each of the models has a particular method. With PHP I'd create a class interface to ensure my model has the methods necessary to do it's job but it seems Python interfaces don't work with Django models.
I'm assuming the way to do this would be to create a base class that extends model.Model which defines the methods I need and I can overwrite them in each API model if necessary. How am I able to do this without Django picking up the "base" class when syncing the database? Is this even the right way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Meta
类的abstract = True
方面。文档: http://docs.djangoproject.com/en/1.3/ref/ models/options/
话虽如此,通常鸭子类型被认为是“Python 方式”,并且您的调用代码应该测试方法是否存在(
if hasattr(instance, 'method_name')
)。也就是说,您比我们更了解您的特定实现,因此您可以使用abstract = True 来获得您想要的行为。 :)You can use the
abstract = True
aspect of theMeta
class.Documentation: http://docs.djangoproject.com/en/1.3/ref/models/options/
With that said, generally duck typing is considered to be "the Python way", and your calling code should test for method presence (
if hasattr(instance, 'method_name')
). That said, you know your particular implementation better than we do, so you can use abstract = True to get the behavior you want. :)我认为这更像是一个Python问题。您当然可以查看 Django 抽象基类 但我建议您做更多Pythonic 的事情,而不用担心尝试强制执行这些类接口。无论您是否实现了该方法,都让调用代码来处理它。
I think this is more of a Python question. You can certainly look at Django abstract base classes but I recommend you do the more pythonic thing and not worry about trying to enforce these class interfaces. Either you implemented the method or you didn't, let the calling code deal with it.