在我们的应用程序中,我们有几个关系和几个模型,我正在尝试实现一个对象的所有相关对象的通用方法,甚至反向对象。在
如果我从我的模型Pessoa
打印._meta.get_fields()
,我会得到这些关系字段(我省略了“普通”字段):
在 在
<ManyToManyRel: cadastroimoveis.pessoa>
<ManyToOneRel: cadastroimoveis.pessoa_pessoa>
<ManyToOneRel: cadastroimoveis.pessoa_pessoa>
<ManyToOneRel: cadastroimoveis.pessoa_itr>
<ManyToManyRel: cadastroimoveis.doc>
<ManyToOneRel: cadastroimoveis.doc_pessoa>
cadastroimoveis.Pessoa.relacoes
cadastroimoveis.Pessoa.itrs
这个特定的模型只有M2M关系,并且所有这些关系都包含一个指定的“through”模型Here。在
如您所见,它重复了它们,一个用于模型,一个用于“通过”中间表(我猜也是一个模型)。对于递归关系,它会重复两次。在
我的问题是,有没有办法让这些不再重复?在
一种知道哪些重复字段“指向”最终相同关系的方法(即使它将两个表分隔开)?因为如果through表有字段,我希望以不同的方式显示它们。在
根据Model _meta API文档,您可以使用它来获取所有相关对象:
^{pr2}$但是“through”表不是自动创建的,而是具体的。在
示例:
<ManyToManyRel: cadastroimoveis.ccir>
<ManyToOneRel: cadastroimoveis.ccir_pessoa>
这两个字段“指向”了相同的关系,一个是中间表,另一个是模型,有没有一种(自动的)方法来知道这两个字段是相关的吗?我找不到他们有什么共同点。在
这样做的原因是,当through表有字段时,我需要对其进行编辑,而不是在模型本身上编辑M2M字段
模型.py:http://pastebin.com/szDfhHQ3我尽我所能清理干净了
对于django1.10,以下代码受
BaseModelForm
代码(Django original)的启发。在如果您有以下关系:
然后,可以这样查询相关字段和属性:
^{pr2}$其他答案肯定帮了我解决这个问题,特别是在我的例子中,我所有的关系都是M2M,并且有一个through表,而且所有的事情都是用AJAX/Javascript完成的,所以我的答案非常JSON-y
目前,它只获得m2m模型的所有表,因为您必须在其中创建对象才能创建关系,但它可以很容易地扩展到获取所有其他关系
这是一个非常难看的代码,但我不太擅长Python,只是想学习一些东西,但我保证它对我的问题很有帮助
例如,我们有这套模型。我从this django example取的。在
这个解决方案看起来有点难看,但可以根据您的需要进行优化。在
^{pr2}$输出:
如您所见,没有
membership
字段。在相关问题 更多 >
编程相关推荐