在管理员中选择链接

时间:2021-06-25 18:02:37

标签: python django django-models

假设我有以下模型(总结):

class Control(models.Model:
    name = models.CharField()
    code = models.CharField(unique=True)
    type = models.CharField()
    subtype = models.CharField()

class List(models.Model):
    type = models.CharField()
    subtype = models.CharField()

在我的数据库中,我的列表填充如下:

     type     |     subtype     
--------------------------------
Information   | Paper
Information   | Digital
Information   | Software
Personal      | System
Processes     | -

为了让 Type 选项出现在下拉列表中而不重复,我创建了以下表单,但我不知道如何做我上面评论的内容,以及是否可以以更正确的方式完成:

def queryset_to_choices(queryset) -> tuple:
    tupla = ((None, None),)

    for i in list(queryset):
        tupla_aux = (i, i)
        tupla = tupla + (tupla_aux,)

    return tupla


class ControlForm(forms.ModelForm):
    type = forms.ChoiceField(
    choices=queryset_to_choices(List.objects.order_by('type').values_list('type', flat=True).distinct())
)
subtipo_activo = forms.ChoiceField(
    choices=queryset_to_choices(List.objects.exclude(subtype=None).order_by('subtype').values_list('subtype', flat=True).distinct())
)

我该怎么做,从管理站点添加新控件时,子类型取决于我选择的类型。例如,如果在类型中选择信息,则在子类型中您只能选择纸张、数字和软件。

我知道从我创建的 URL 可以使用 AJAX,但我不知道如何从管理员那里让它像这样工作。

如果有人能帮我解决这个问题,我将不胜感激,因为我读过一些东西,但我找不到。

更新(使用外键):

型号:

class List(models.Model):
type = models.CharField(
    max_length=255,
)
subtype = models.CharField(
    max_length=255,
    blank=True,
)

def __str__(self):
    return f'{self.type} - {self.subtype}'

class Meta:
    ordering = ['type', 'subtype']


class Control(models.Model):
    name = models.CharField(
        max_length=255,
    )
    type = models.ForeignKey(
        to=List,
        on_delete=models.CASCADE,
        related_name='control_type'
    )
    subtype = models.ForeignKey(
        to=List,
        on_delete=models.CASCADE,
        related_name='control_subtype'
    )

    class Meta:
        ordering = ['name']

现在呢?当我转到管理员时,它看起来像这样(两个字段中都相同):

enter image description here

enter image description here

0 个答案:

没有答案