[英]Dependent fields in Django
I'm in the process of designing models for a Django
app and I can't quite work out how to approach a problem. 我正在为
Django
应用程序设计模型,但我还不太想办法解决问题。
I have 3 models. 我有3个模型。
Server
, Module
, and Device
. Server
, Module
和Device
。
Server
is a server that a module could run on. Server
是可以在其上运行模块的服务器。 Module
runs on a server, and contains devices. Module
在服务器上运行,并包含设备。
The problem with Devices
is that the name is always a field, but the attributes could change. Devices
的问题在于名称始终是一个字段,但是属性可能会更改。
I considered just putting a JSON
value in attributes but I couldn't figure out how to do that with Django admin. 我考虑只是在属性中放置一个
JSON
值,但我不知道如何使用Django admin来做到这一点。
Basically the user will enter a name for the device and depending on which module it is attached to, show various different fields to fill in. 基本上,用户将输入设备的名称,并取决于设备所连接的模块,并显示要填写的各种不同字段。
For example: 例如:
module rfm_ninjablock:
Device fields would be "name" and "code"
module LimitlessLED
Device fields would be "name", "controller", "group" and "LightID"
Is there a straightforward way to do it or am I going about it the wrong way? 有没有简单的方法可以做到这一点,还是我做错了方法?
One way to do this is to make a fourth model: DeviceAttribute
. 一种实现方法是建立第四个模型:
DeviceAttribute
。
Each Device has a name and has zero or more DeviceAttribute
s. 每个设备都有一个名称,并且具有零个或多个
DeviceAttribute
。
A DeviceAttribute
has two fields: key
and value
. DeviceAttribute
具有两个字段: key
和value
。
Alternatively, you could use the JSON you suggested, but you wouldn't be able to query on it or update it as easily. 另外,您可以使用建议的JSON,但无法对其进行查询或更新。 It's a bit of an anti-pattern.
这有点反模式。
UPDATE: If you have several "classes" of Device
s, then rather than having arbitrary attributes, you can achieve type-safety by subclassing your models. 更新:如果您有
Device
的多个“类”,则可以通过子类化模型来实现类型安全,而不是具有任意属性。
There are several ways to do this. 有几种方法可以做到这一点。 I have often used the multi-table approach.
我经常使用多表方法。
It creates a OneToOneField
between DeviceSubclassA
and Device
, and between DeviceSubclassB
and Device
. 它创建了一个
OneToOneField
之间DeviceSubclassA
和Device
之间,以及DeviceSubclassB
和Device
。
You can add certain fields to DeviceSubclassA
, and different fields to DeviceSubclassB
. 您可以将某些字段添加到
DeviceSubclassA
,并将不同的字段添加到DeviceSubclassB
。 The common name
attribute is on the Device
parent model. 公用
name
属性在Device
父模型上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.