在ModelForm中的排序选择ManytoManyField DJANGO [英] Ordering Choices in ModelForm ManytoManyField DJANGO
本文介绍了在ModelForm中的排序选择ManytoManyField DJANGO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的models.py
I have in my models.py
class Business(models.Model):
industry = models.models.ManyToManyField(Industry)
in forms.py
in forms.py
class BusinessForm(forms.ModelForm):
class Meta:
model = Business
当我呈现表单时,行业名称将显示在多个选择框中。
When I render the form, the industry names appear in a multiple select box. What do I do to make the industry names in alphabetical order?
推荐答案
有几种方法:
您可以在每个表单的基础上重写查询集排序,设置排序元类选项,或使用排序方法覆盖模型管理器查询集。
You can override the queryset ordering on a per-form basis, set the ordering meta class option, or override the model manager queryset with an ordering method.
class IndustryManager(models.Manager):
def get_query_set(self):
return (
super(IndustryManager, self)
.get_query_set()
.order_by('name')
)
class Industry(models.Model):
name = models.CharField(max_length=128)
objects = IndustryManager()
指定全局元选项排序
Specify global meta option ordering
class Industry(models.Model):
name = models.CharField(max_length=128)
class Meta:
ordering = ['name']
每个订单
Per form ordering
class MyForm(forms.ModelForm):
class Meta:
model = Business
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['industry'].queryset = Industry.objects.order_by('name')
如果您正在处理django管理员,还有一个名为formfield_for_manytomany的快捷方式。
There's also a shortcut called formfield_for_manytomany if you are dealing with the django admin.
这篇关于在ModelForm中的排序选择ManytoManyField DJANGO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文