Search code examples
djangoforeign-keysparent-childmodelslimit-choices-to

Django ForeignKey limit_choices_to multiple child elements


I have the following models:

class Person(models.Model):
    # fields

class Teacher(Person):
    # fields

class Student(Person):
    # fields
    teacher = models.ForeignKey(teacher)

class Staff(Person):
    # fields

class SomeModel(models.Model):
    # fields
    point_person = models.ForeignKey(Person)

But I want to limit my "point_person" to Teacher and Student only. How can I do this?


Solution

  • I would offer to implement a custom manager, probably overriding the get_queryset. I can see 2 solutions to get only those Parent, who have ChildA and/or ChildB.

    • If one Parent never has ChildA and ChildB same time (or any other combination), you can add an extra field (db column) to Parent, which indicates what is the class of its child object, if any. In get_queryset of your custom manager you always check this field.
    • If one Parent can have multiple classes of Child simultaneously, of if you don't want to add an extra column, then you override get_queryset, to actually select from ChildA and ChildB, and combine the querysets afterwards into a single queryset.