【问题标题】:Django ModelForm: search filter many to many field widgetDjango ModelForm:搜索过滤器多对多字段小部件
【发布时间】:2021-11-22 14:38:28
【问题描述】:

我正在使用这个模型:

class Sample(models.Model):
    id_sample = models.AutoField(primary_key=True)
    name = models.CharField(unique=True, max_length=20)
    sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe')
    pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools")

pools 是此模型中的 m2m 字段:

class Pool(models.Model):
    id_pool = models.AutoField(primary_key=True)
    name = models.CharField(unique=True, max_length=50, verbose_name="Pool")
    samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres")

我创建了这个ModelForm

class FormulariMostra(ModelForm):
    class Meta:
        model = Sample
        fields = ("name", "sample_id_sex", "pools",)

它工作正常,但问题是pools 字段可以包含数千个值。在这里提出了类似的问题:Django: Search many to many field while creating object

我尝试了https://github.com/ExoticObjects/django-better-filter-widget 推荐的这个小部件,但它似乎已经过时了......

还有其他选择吗?我知道这可以在管理员中完成,但我想在 ModelForm 中完成。

【问题讨论】:

    标签: django django-forms widget


    【解决方案1】:

    autocomplete_fieldshttps://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

    所以你可以写:

    class FormulariMostra(ModelForm):
        class Meta:
            model = Sample
            autocomplete_fields = ["pools"]
            fields = ("name", "sample_id_sex", "pools",)
    

    或者还有raw_id_fields https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

    【讨论】:

    猜你喜欢
    • 2020-03-20
    • 2011-01-14
    • 1970-01-01
    • 2018-06-07
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多