Django 表單模型選擇框如何使用分組
起步
Django 表單中有兩種字段類型可以使用選擇框: ChoiceField
和 ModelChoiceField
。
對于 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本身沒有提供解決方案。
在 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)
最后,在表單中可以如下進(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')
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Django ORM 聚合查詢和分組查詢實現(xiàn)詳解
- django 中的聚合函數(shù),分組函數(shù),F(xiàn) 查詢,Q查詢
- Django Aggregation聚合使用方法解析
- django的聚合函數(shù)和aggregate、annotate方法使用詳解
- Django之無名分組和有名分組的實現(xiàn)
- 對Django中的權(quán)限和分組管理實例講解
- django框架使用views.py的函數(shù)對表進(jìn)行增刪改查內(nèi)容操作詳解【models.py中表的創(chuàng)建、views.py中函數(shù)的使用,基于對象的跨表查詢】
- django框架基于queryset和雙下劃線的跨表查詢操作詳解
- Django中自定義查詢對象的具體使用
- django框架F&Q 聚合與分組操作示例
相關(guān)文章
用Python編寫腳本使IE實現(xiàn)代理上網(wǎng)的教程
這篇文章主要介紹了用Python編寫腳本使IE實現(xiàn)代理上網(wǎng)的教程,“著名的”goagent代理也是基于同樣原理實現(xiàn),需要的朋友可以參考下2015-04-04學(xué)會這29個常用函數(shù),你就是Pandas專家
Pandas?無疑是?Python?處理表格數(shù)據(jù)最好的庫之一,但是很多新手無從下手,這里總結(jié)出最常用的?29?個函數(shù),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-11-11Python接口傳輸url與flask數(shù)據(jù)詳解
這篇文章主要介紹了Python通過接口傳輸url與flask數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09