Django ModelForm:搜索过滤器多对多字段小部件



我正在使用这个模型:

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:创建对象时搜索多对多字段

我尝试了这个小工具推荐https://github.com/ExoticObjects/django-better-filter-widget,但它似乎过时了…

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

autocomplete_fields: https://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_fieldshttps://docs.djangoproject.com/en/3.2/ref/contrib/admin/django.contrib.admin.ModelAdmin.raw_id_fields

相关内容

  • 没有找到相关文章

最新更新