简体   繁体   English

Django与动态模型的关系

[英]Django and Dynamic model relationships

I have one main model : 我有一个主要模型:

ToolBox

and three other models : 和其他三个模型:

Hammer
Nail
Plier

Obviously a ToolBox can contain any combination of Hammers, Nails or Pliers. 显然,工具箱可以包含锤子,钉子或钳子的任意组合。

Using Django, what is a good ORM representation of this dynamic type of relationship? 使用Django,这种动态关系类型的ORM代表是什么? Bare in mind that each of these models can have its own rich set of attributes so a simple type field won't do the job. 切记,这些模型中的每一个都可以具有自己丰富的属性集,因此简单的type字段将无法完成任务。 I am also wondering how the admin interface in Django can be fine tuned to this dynamic type of thing if it works. 我也想知道,如果Django的管理界面能正常工作,该界面如何进行微调。

I am not sure what you mean by dynamic, your example is quite typical I think. 我不确定您所说的动态含义是什么,我认为您的例子很典型。

But anyway, in order to avoid the situation: 但是无论如何,为了避免这种情况:

Toolbox
    many2many(Hammer)
    many2many(Nail)
    etc... (add new m2m field every time you add another tool class)

I would do it like this: 我会这样做:

Toolbox

Hammer
    foreignkey(Toolbox)

Nail
    foreignkey(Toolbox)

This will make things much easier to implement (use toolbox.hammer_set, etc). 这将使事情更容易实现(使用toolbox.hammer_set等)。 If the Hammer, Nail, etc have some fields in common you can also define an abstract base class (eg Tool) that holds all common fields. 如果Hammer,Nail等具有一些共同的字段,您还可以定义一个包含所有共同字段的抽象基类(例如Tool)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM