最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Django 表單模型選擇框如何使用分組

 更新時間:2019年05月16日 08:21:28   作者:棲遲於一丘  
這篇文章主要介紹了Django 表單模型選擇框如何使用分組,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

起步

Django 表單中有兩種字段類型可以使用選擇框: ChoiceFieldModelChoiceField 。

對于 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> 標簽:

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本身沒有提供解決方案。

https://code.djangoproject.com/ticket/27331 中提供了一個很好的解決方案。

首先為需要分類的類型創(chuàng)建模型,在另一個模型中用外鍵關(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)建一個新的表單 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)

最后,在表單中可以如下進行使用:

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python人工智能tensorflow函數(shù)tf.get_collection使用方法

    python人工智能tensorflow函數(shù)tf.get_collection使用方法

    這篇文章主要為大家介紹了python人工智能tensorflow函數(shù)tf.get_collection使用方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • Python線程池thread?pool創(chuàng)建使用及實例代碼分享

    Python線程池thread?pool創(chuàng)建使用及實例代碼分享

    這篇文章主要介紹了Python線程池(thread?pool)創(chuàng)建使用及實例代碼分享,文章圍繞主題展開詳細的內(nèi)容介紹具有一定的參考價值,需要的小伙伴可以參考一下
    2022-06-06
  • Python進階學習之特殊方法實例詳析

    Python進階學習之特殊方法實例詳析

    一般說來,特殊的方法都被用來模仿某個行為。下面這篇文章主要給大家介紹了關(guān)于Python進階學習之特殊方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起看看吧。
    2017-12-12
  • python獲取系統(tǒng)內(nèi)存占用信息的實例方法

    python獲取系統(tǒng)內(nèi)存占用信息的實例方法

    在本篇文章里小編給大家整理的是關(guān)于python獲取系統(tǒng)內(nèi)存占用信息的實例方法,有需要的朋友們可以參考學習下。
    2020-07-07
  • 最新評論

    台中县| 长丰县| 嘉兴市| 麻江县| 大理市| 达孜县| 霍州市| 福州市| 衡山县| 周宁县| 辰溪县| 凤山市| 进贤县| 万宁市| 长宁县| 夏邑县| 凤城市| 景泰县| 大新县| 方正县| 辛集市| 横山县| 上思县| 吉林省| 白朗县| 峨眉山市| 轮台县| 宜昌市| 淮阳县| 建湖县| 凉山| 平远县| 南京市| 岗巴县| 墨江| 清河县| 镇康县| 桐柏县| 内丘县| 犍为县| 崇礼县|