Swimming bird
Swimming bird

Reputation: 77

Django ModelForm: search filter many to many field widget

I'm working with this model:

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 is a m2m field from this model:

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

I created this ModelForm:

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

It works fine but the problem is that the pools field can contain thousands of values. A similar question was asked here: Django: Search many to many field while creating object

I tried this widget recommended there https://github.com/ExoticObjects/django-better-filter-widget but it seems outdated...

Is there any alternative? I know this can be done in the admin but I want to do it in the ModelForm.

Upvotes: 4

Views: 1078

Answers (1)

Slava
Slava

Reputation: 2007

There are autocomplete_fields for that: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

So you can write:

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

or there is also raw_id_fields https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

Upvotes: 4

Related Questions