Django 外键作为 optgroups 的下拉选项

Django foreign key as dropdown choice with optgroups

我有以下 django 模型:

class BaseModel(models.Model):
    uuid = UUIDField()
    created = models.DateTimeField(auto_now_add=True, null=True)
    modified = models.DateTimeField(auto_now=True, null=True)

    class Meta:
        abstract = True

class Company(BaseModel):
    title = models.CharField(_(u'Title'), max_length=128)

class Profile(BaseModel):
    company = models.ForeignKey(Company, verbose_name='Company')
    user = models.OneToOneField(User, verbose_name='User', null=True, blank=True)

class ServiceCategory(BaseModel):
    company = models.ForeignKey(Company)
    title = models.CharField(_(u'Title'), max_length=64)

class Service(BaseModel):
    category = models.ForeignKey(ServiceCategory)
    title = models.CharField(_(u'Title'), max_length=64)

如您所见,每个 ServiceCategory 都有 Company 外键。公司还用于对用户进行分组(每个用户与个人资料具有一对一的关系,其中公司是个人资料的外键。

无论如何,我需要一个带有下拉列表的表单字段,它将显示公司中所有可用的服务(使用 optgroup)按类别分组(类别不可选择),例如:

类别 1

类别 2

有什么实现方法的建议吗?

DJ 表单支持 optgroup,但是您需要为表单字段提供自定义格式的选择列表。

# in the form init
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

    # you need to manual format for queryset to be in this format
    service_choices = (
     ('Cat1', (
       ('service1_id', 'Service1'),
       ('service2_id', 'Service2'),
     ),
     ('Cat2', (
       ('service3_id', 'Service3'),
       ('service4_id', 'Service4'),
     ),
    )

self.fields['your_service_field'].choices = service_choices