首页 > 解决方案 > Django - create child models

问题描述

Let say that the model name is BHA, and I populate this field. In Django-Admin homepage, I will have a tab looks like this:

MY_APP_NAME

BHA List
Other Model 1
Other Model 2

Upon clicking BHA List, I will be navigate to a page that has a list of populated BHA:

BHA List

BHA_1
BHA_2
BHA_3
BHA_4

And each BHA needs a separate table that has their own information. So all BHA's (BHA_1, BHA_2, BHA_3, BHA_4) will have exact same child field Bit data, Sensor Data, Component Data. And Each of these sub-fields will have its own subfields too. How should I design my models.py to make this work? Can anyone provide any example code set that enables this feature?

So far I know only a really basic models.py structure that looks like this:

class SomeModel(models.Model):
    field_1 = models.CharField(max_length=100, primary_key=True)
    field_2 = models.CharField(max_length=100)
    field_3 = models.CharField(max_length=100)

标签: pythondjangodjango-modelsforeign-keys

解决方案


从技术上讲,这些不是子类。他们没有遗产。如果我理解正确,您将不得不使用ForeignKey.

BHA(models.Model):
   bha_name = models.CharField(params)

BitData(models.Model):
    bha = models.ForeignKey(params with reference to BHA)
    model_field = models.CharField(params)

SensorData(models.Model):
    bha = models.ForeignKey(params with reference to BHA)
    model_field = models.CharField(params)

要以您想要的方式在您的页面上查看它们,可能需要更改所使用的小部件。

您还必须在页面上引用您的所有模型。多种模型形式


推荐阅读