django - ModelForm ManytoManyField DJANGO 中的排序选择

标签 django django-models django-forms

我的models.py中有

class Business(models.Model):
   industry = models.models.ManyToManyField(Industry)

在forms.py中
class BusinessForm(forms.ModelForm):
    class Meta:
        model = Business

当我呈现表单时,行业名称出现在多选框中。如何按字母顺序制作行业名称?

最佳答案

有几种方式:

您可以基于每个表单覆盖查询集排序,设置排序元类选项,或使用排序方法覆盖模型管理器查询集。

覆盖全局模型管理器查询集

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

指定全局元选项排序
class Industry(models.Model):
    name = models.CharField(max_length=128)

    class Meta:
        ordering = ['name']

按表格订购
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 的快捷方式。

关于django - ModelForm ManytoManyField DJANGO 中的排序选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541477/

相关文章:

python - 我可以在 django 中使用 python 操作系统/系统模块吗

python - 如何获得 MINIO 访问权限和 key ?

django - 无法连接到redis ://localhost:6379/0: Error 111 connecting to localhost:6379. 连接被拒绝

python - 通过 Django 查询 salesforce 时出现 SalesforceMalformedRequest 错误

python - 在 Django 模板中访问模型数据

django - 如何在Django Rest Framework ModelSerializer中覆盖模型字段验证

python - 无法在 django 中为 forms.ChoiceField 设置初始值

Django formset_factory vs modelformset_factory vs inlineformset_factory

python - Django 对象存在

python - 如何在Django Form的clean()方法中获取auto_id?