簡體   English   中英

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

  • 服務1
  • 服務2
  • 服務3

類別2

  • 服務4
  • 服務5

任何建議如何實現這一目標?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM