未加星标

How to Implement Grouped Model Choice Field

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二05 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

The Django forms API have two field types to work with multiple options: ChoiceField and ModelChoiceField .

Both use select input as the default widget and they work in a similar way, except that ModelChoiceField is designed to handle QuerySets and work with foreign key relationships.

A basic implementation using a ChoiceField would be:

class ExpenseForm(forms.Form): CHOICES = ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), (21, 'Books'), (22, 'Games'), (31, 'Groceries'), (32, 'Restaurants'), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES)


How to Implement Grouped Model Choice Field
Grouped Choice Field

You can also organize the choices in groups to generate the <optgroup> tags like this:

class ExpenseForm(forms.Form): CHOICES = ( ('Debt', ( (11, 'Credit Card'), (12, 'Student Loans'), (13, 'Taxes'), )), ('Entertainment', ( (21, 'Books'), (22, 'Games'), )), ('Everyday', ( (31, 'Groceries'), (32, 'Restaurants'), )), ) amount = forms.DecimalField() date = forms.DateField() category = forms.ChoiceField(choices=CHOICES)


How to Implement Grouped Model Choice Field
Grouped Model Choice Field

When you are using a ModelChoiceField unfortunately there is no built-in solution.

Recently I found a nice solution on Django’s ticket tracker , where someone proposed adding an opt_group argument to the ModelChoiceField .

While the discussion is still ongoing, Simon Charette proposed a really good solution.

Let’s see how we can integrate it in our project.

First consider the following models:

models.py

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

So now our category instead of being a regular choices field it is now a model and the Expense model have a relationship with it using a foreign key.

If we create a ModelForm using this model, the result will be very similar to.

To simulate a grouped categories you will need the code below. First create a new module named fields.py :

fields.py 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)

And here is how you use it in your forms:

forms.py

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


How to Implement Grouped Model Choice Field

Because in the example above I used a self-referencing relationship I had to add the exclude(parent=None) to hide the “group categories” from showing up in the select input as a valid option.

Further Reading

You can download the code used in this tutorial from GitHub: github.com/sibtc/django-grouped-choice-field-example

Credits to the solution Simon Charette on Django Ticket Track .

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

分页:12
转载请注明
本文标题:How to Implement Grouped Model Choice Field
本站链接:https://www.codesec.net/view/627979.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(22)