Home > front end >  Django - ForeignKey Filter Choices
Django - ForeignKey Filter Choices

Time:11-12

I'd like to filter the choices that a user can choose in my ForeignKey Field. I basically have a ForeignKey for the subject of the Test and the actual topic of the Test. These topics come from a different model and are linked to a subject. Now I'd like to filter the choices to only include the topics that are linked to the currently selected subject. Is that possible and if so, how?

models.py

class Test(models.Model):
    student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True)
    thema = models.ForeignKey(Thema, on_delete=models.CASCADE, blank=True, null=True)
    school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True)
    grade = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(6)], blank=True, null=True)
    date = models.DateField(default=datetime.date.today)

    def save(self, *args, **kwargs):
        if not self.school_class and self.student:
            self.school_class = self.student.klasse
        return super().save(*args, **kwargs)


class Thema(models.Model):
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True)
    thema = models.CharField(max_length=50)

CodePudding user response:

If you use django forms you can use the model choice field. In your view you can set your queryset of this choicefield. Zo you can filter it.

fields['your model field'].queryset = yourmodel.objects.filter(your filter parameters)

CodePudding user response:

I think what you are looking for ideally would be ForeignKey.limit_choices_to

Please see the docs:

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

You can limit the choices available at a model level, which is enforced throughout the django app, including forms automatically.

  • Related