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 ModelForm
s, 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 AttendanceList
s that are already referring to that Assignment
will not be updated, removed or prevent updating.