Django - 模型外墙 [英] Django - Models Façade

查看:138
本文介绍了Django - 模型外墙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Django项目开发一个服务器端的API,但是我已经提出了在models.py文件中的每个模型声明中定义的一系列方法。所以我想要创建一种Façade类来处理API方法,只有模型才能使用它们的属性。

我曾经有这样的结构:

I'm trying to develop a server-side API for my Django project, but I've came up with a whole bunch of methods defined in every model declaration in the models.py files. So I thought to create a sort of Façade classes to handle the API method, leaving the models only with their properties.
I used to have this structure:

# models.py

class MyModel(models.Model):
    prop1 = ...
    prop2 = ...

    def f1(self):
        pass
    def f2(self):
        pass

虽然现在II有这样一个:

While now I I have this one:

# models.py

class MyModel(models.Model):
    prop1 = ...
    prop2 = ...

# wrappers.py

from myapp import models


class MyModel(models.MyModel):

    def f1(self):
        pass
    def f2(self):
        pass

这是非常有趣的,当我写下来,因为它允许我分离功能的定义,而不会丢失任何功能。但是,当我试图测试新的数据模型时,我很困惑。

This was pretty interesting while I was writing it down, because it allowed me to separate definition of functionality without losing none of them. However, when I tried to test the new data model, I got very confused.

$ python manage.py shell
Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from myapp.wrappers import MyModel
>>> MyModel
<class 'MyProject.myapp.models.MyModel'>

WTF正在进行!当我要求包装器时,为什么要获得模型类?

当然,这将保留模型的所有属性,但显然缺乏在包装器中定义的所有方法。

我希望你能帮助我,因为对我来说这完全是废话。谢谢你的帮助。

WTF is going on here!? Why do I get the model class when I'm asking for the "wrapper" one instead?
Of course, this keeps all the properties of the model but obviously lacks all of the methods defined in the wrapper.
I hope you can help me with this because it's a completely nonsense for me. Thank you for your help.

推荐答案

文档代理模型。那些会按照你想要的。

A little further down in the documentation is "proxy models". Those will do as you want.

这篇关于Django - 模型外墙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆