Django: how to limit_choices_to when using custom staging table

Let me start by saying that I'm working with a legacy database, so avoiding a custom staging table is not an option.

I am looking for an alternative way to get the functionality limit_choices_to

, since I only need to present the parameters marked with t21> in the Sampletype

Model in my ModelForm:

class PlanetForm(ModelForm):
    class Meta:
        model = Planet
        fields = ['name', 'samples']


Here's a simplified view of my models.

class Planet(models.Model):
    name= models.CharField(unique=True, max_length=256)
    samples = models.ManyToManyField('Sampletype', through='Sample')

class Sample(models.Model):
    planet = models.ForeignKey(Planet, models.DO_NOTHING)
    sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING)

class Sampletype(models.Model):
    name = models.CharField(unique=True, max_length=256)
    sample_option = models.BooleanField(default=True)



- intermediate table. Usually, if the project was started with Django, I could simply define the ManyToManyField declaration as:

samples = models.ManyToManyField('Sampletype', limit_choices_to={'sample_option'=True})


But that's not an option. So how do I get this functionality? In its documentation, Django clearly states that:

limit_choices_to does not affect the use of a ManyToManyField with a custom staging table specified using the pass-through parameter.

But they don't provide any information on how to get this limit when you have a custom staging table.

I tried to set the parameter limit_choices_to

to ForeignKey

in the model Sample

like so:

sampletype = models.ForeignKey('Sampletype', models.DO_NOTHING, limit_choices_to={'sample_option': True})


but that didn't make any difference.

Strange, I don't find an answer to this on the internet and obviously other people have to do this in their projects, so I guess the solution is really simple, but I can't figure it out.

Thanks in advance for any help or suggestions.


source to share

1 answer

You can set the selection in the __init__

form method :

class PlanetForm(ModelForm):

    class Meta:
        model = Planet
        fields = ['name', 'samples']

    def __init__(self, *args, **kwargs):
         super(PlanetForm, self).__init__(*args, **kwargs)

         sample_choices = list(
             Sampletype.objects.filter(sample_option=True).values_list('id', 'name')
         # set these choices on the 'samples' field.
         self.fields['samples'].choices = sample_choices




All Articles