django: smart-select ChainedForeignKey / chained dropdown in admin

899 views Asked by At

Hej! :)

I have 5 models which are connected hierarchical with each other. Section -> division -> group -> class -> wz

one section can have multiple divisions, but one division can only have one section (and so on). Therefor I have ForeignKeys set:

# 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)

I than have a model where all those are integrated as M2M fields with a dropdown option. My goal is to only get the divisions which are in the already selected section in the admin area. (and so on)

I tried smart-select 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,
    )

The organisation and dropdown in the admin area do not change at all and my view with a table of all my results tells me ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'nace_divisions_id'. (207) (SQLExecDirectW)")

With the ChainedManyToManyField nothing at all happens. Does anybody know what's going wrong? Any help appreciated! :)

1

There are 1 answers

5
LCM-DEVELOPER On

nace_sections is specified as models.ManyToManyField in your code

1.Change from ManyToManyField to ForeignKey.

2.Rename chained_model_field values

-->nace_sections to nace_section
-->nace_divisions to 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,
)