小編給大家分享一下Django表單模型選擇框怎么使用分組,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

起步
Django 表單中有兩種字段類型可以使用選擇框: ChoiceField 和 ModelChoiceField 。
對(duì)于 ChoiceField 的基本使用是:
class ExpenseForm(forms.Form): CHOICES = ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), (21, 'Books'), (22, 'Games'), (31, 'Groceries'), (32, 'Restaurants'), ) date = forms.DateField() category = forms.ChoiceField(choices=CHOICES)
它能渲染出:

使用分組下拉框
還可以使用如下方式生成 <optgourp> 標(biāo)簽:
class ExpenseForm(forms.Form):
  CHOICES = (
    ('Debt', (
      (11, 'Credit Card'),
      (12, 'Student Loans'),
      (13, 'Taxes'),
    )),
    ('Entertainment', (
      (21, 'Books'),
      (22, 'Games'),
    )),
    ('Everyday', (
      (31, 'Groceries'),
      (32, 'Restaurants'),
    )),
  )
  date = forms.DateField()
  category = forms.ChoiceField(choices=CHOICES)能夠渲染為:

分組模型下拉框
如果使用的是 ModelChoiceField ,那抱歉,Django本身沒(méi)有提供解決方案。
在 https://code.djangoproject.com/ticket/27331 中提供了一個(gè)很好的解決方案。
首先為需要分類的類型創(chuàng)建模型,在另一個(gè)模型中用外鍵關(guān)聯(lián)它:
from django.db import models
class Category(models.Model):
  name = models.CharField(max_length=30)
  parent = models.ForeignKey('Category', on_delete=models.CASCADE, null=True)
  def __str__(self):
    return self.name
class Expense(models.Model):
  amount = models.DecimalField(max_digits=10, decimal_places=2)
  date = models.DateField()
  category = models.ForeignKey(Category, on_delete=models.CASCADE)
  def __str__(self):
    return self.amount其次,創(chuàng)建一個(gè)新的表單 Field 類型:
from functools import partial
from itertools import groupby
from operator import attrgetter
from django.forms.models import ModelChoiceIterator, ModelChoiceField
class GroupedModelChoiceIterator(ModelChoiceIterator):
  def __init__(self, field, groupby):
    self.groupby = groupby
    super().__init__(field)
  def __iter__(self):
    if self.field.empty_label is not None:
      yield ("", self.field.empty_label)
    queryset = self.queryset
    # Can't use iterator() when queryset uses prefetch_related()
    if not queryset._prefetch_related_lookups:
      queryset = queryset.iterator()
    for group, objs in groupby(queryset, self.groupby):
      yield (group, [self.choice(obj) for obj in objs])
class GroupedModelChoiceField(ModelChoiceField):
  def __init__(self, *args, choices_groupby, **kwargs):
    if isinstance(choices_groupby, str):
      choices_groupby = attrgetter(choices_groupby)
    elif not callable(choices_groupby):
      raise TypeError('choices_groupby must either be a str or a callable accepting a single argument')
    self.iterator = partial(GroupedModelChoiceIterator, groupby=choices_groupby)
    super().__init__(*args, **kwargs)最后,在表單中可以如下進(jìn)行使用:
from django import forms
from .fields import GroupedModelChoiceField
from .models import Category, Expense
class ExpenseForm(forms.ModelForm):
  category = GroupedModelChoiceField(
    queryset=Category.objects.exclude(parent=None), 
    choices_groupby='parent'
  )
  class Meta:
    model = Expense
    fields = ('amount', 'date', 'category')以上是“Django表單模型選擇框怎么使用分組”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
                當(dāng)前題目:Django表單模型選擇框怎么使用分組-創(chuàng)新互聯(lián)
                
                瀏覽路徑:http://www.yijiale78.com/article44/dpcehe.html
            
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、小程序開(kāi)發(fā)、ChatGPT、商城網(wǎng)站、微信小程序、手機(jī)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
