[Answered ]-Django model foreign key, filtering?

1👍

You can work with the limit_choices_to=… parameter [Django-doc]:

class AttendanceList(models.Model):
    what_to_attend = models.ForeignKey(
        Assignment,
        on_delete=models.CASCADE,
        limit_choices_to={'is_attendable': True}
    )

This will automatically apply filtering for the ModelForms, and the forms in a ModelAdmin as well as in serializers.

This will however only filter when creating or updating an AttendanceList: if later the Assignment sets is_attendable to False, then the AttendanceLists that are already referring to that Assignment will not be updated, removed or prevent updating.

Leave a comment