首页 > 解决方案 > 模型设计django

问题描述

该模型如下所示。Whereapps是一个字段,它只能具有app1并且app2可以作为将来增加的选择。此外,每个应用程序选择 ( app1, app2) 应该是一个模型,其中包含表示特征的字段。如何在 Django 模型中实现这一点。

apps:
      app1:
        feature_app1_1: "Data"
        feature_app1_2: "Data"
      app2:
        feature_app2_1: "Data"
        feature_app2_2: "Data"

标签: djangodjango-models

解决方案


这听起来像你需要多对多的关系。多对多字段将限制对您创建的模型的选择,因此如果您只有 2 个应用程序,那么这些将是您唯一的选择。随着您添加更多,它们会出现。

所以,我想你想要这样的东西:

你说“应用程序”是一个字段,所以如果那是父模型上的一个字段。

Class Foo(models.Model):
    apps = models.ManyToManyField(App) 


Class App(models.Model):
    name = models.Charfield(max_legnth=100) #App name
    features = models.ManytoManyField(Feature)


Class Feature(models.Model):
    name = models.Charfield(max_legnth=100) #Feature name
    ...... # Your data fields here. 

您的父类将有一个多对多字段(“应用程序”)链接到您想要的所有应用程序,然后每个应用程序将链接到您需要的每个功能(“功能”)。然后每个特征都包含数据。


推荐阅读