ManyToManyField limit choices to dynamic foreign model

3.2k Views Asked by At
class TrialRun(models.Model):
    product = models.ForeignKey(NewProduct, verbose_name='Product',)

class Component(models.Model):
    product = models.ForeignKey(NewProduct, verbose_name='Product',)

class TrialIssue(models.Model):
    trialrun = models.ForeignKey(TrialRun, verbose_name='Trial Run',)
    components = models.ManyToManyField(
        Component,limit_choices_to{product=trialrun.product})

How could I realize the thinking of (Component, limit_choices_to={product=trialrun.product})?

i can not use the following

def __init__(self, *args, **kwargs):
    super(TrialIssueForm, self).__init__(*args, **kwargs)
    # make sure we're editing a saved model
    if self.instance.id:
        self.fields['components'].queryset = Component.objects.filter(product=self.instance.trialrun.product)
1

There are 1 best solutions below

3
On

There is no way to define it on the database level, so you need to do this inside a form. There is an example on Creating a dynamic choice field for a ForeignKey field, but it should be able to change it to work with ManyToManyFields as well.

If you also want it checked inside the model, you have to add your own custom validator as described here: https://docs.djangoproject.com/en/1.6/ref/models/instances/#validating-objects