Hej!:(
我有5个模型,它们是分层连接的。章节->分区->组->类->wz
一个分区可以有多个分区,但一个分区只能有一个分区(依此类推(。为此,我设置了ForeignKeys:
# models.py
class NaceSection(models.Model):
code = models.CharField(max_length=1, unique=True)
description_english = models.CharField(max_length=500)
class NaceDivision(models.Model):
code = models.CharField(max_length=2, unique=True)
nace_section = models.ForeignKey(NaceSection, on_delete=models.CASCADE, related_name="nace_section")
description_english = models.CharField(max_length=500)
class NaceGroup(models.Model):
nace_division = models.ForeignKey(NaceDivision, on_delete=models.CASCADE, related_name="nace_division")
code = models.CharField(max_length=4, unique=True)
description_english = models.CharField(max_length=500)
我有一个模型,所有这些都集成为M2M字段,并带有下拉选项。我的目标是只获得管理区域中已经选择的分区。(等等(
我尝试了智能选择ChainedForeignKey:
# models.py
class Institution(models.Model):
nace_sections = models.ManyToManyField(
NaceSection,
related_name="nace_sections"
)
nace_divisions = ChainedForeignKey(
NaceDivision,
chained_field="nace_sections",
chained_model_field='nace_sections',
blank=True,
)
nace_group = ChainedForeignKey(
NaceGroup,
chained_field="nace_divisions",
chained_model_field='nace_divisions',
blank=True,
)
管理区域中的组织和下拉列表根本没有改变,我的所有结果的表格告诉我('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'nace_divisions_id'. (207) (SQLExecDirectW)")
有了ChainedManyToManyField,什么都不会发生。有人知道出了什么问题吗?感谢您的帮助!:(
nace_sections被指定为模型。代码中的ManyToManyField
1.从ManyToManyField更改为ForeignKey。
2.重命名chained_model_field值
-->nace_sections到nace_section
-->nace_divisions到nace_division
class Institution(models.Model):
nace_sections = models.ForeignKey(
NaceSection,
related_name="nace_sections"
, on_delete=models.CASCADE
)
nace_divisions = ChainedForeignKey(
NaceDivision,
chained_field="nace_sections",
chained_model_field='nace_section',
blank=True,
)
nace_group = ChainedForeignKey(
NaceGroup,
chained_field="nace_divisions",
chained_model_field='nace_division',
blank=True,
)