Home > Blockchain >  Django model foreign key, filtering?
Django model foreign key, filtering?

Time:04-14

Let's say I have models like that:

class Assignment(models.Model):
  name = [...]
  is_attendable = models.BooleanField([...])

class AttendanceList(models.Model):
 what_to_attend = models.ForeignKey(Assignment, on_delete=models.CASCADE)
 who_attends_it = [...]

So if I set is_attendable to False, it shouldn't be listed on the attendance list. It's like filtering the foreign key's query... How could I do that?

CodePudding user response:

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.

  • Related