[Fixed]-Django- getting a list of foreign key objects


You can use a subquery with __in:


(Note, your naming is a bit odd here: usually the child is the one with the foreign key, since it assumes that a parent can have multiple children.)


I think you may want to refactor your models to be something like:

class ParentModel(models.Model):
    name = models.CharField()

class ChildModel(models.Model):
    name = models.CharField()
    parent = models.ForeignKey(ParentModel)

Then you can just do the following to receive a queryset list of ChildModel:


This would be interpreted as “each ParentModel can have many ChildModel’s.”


This one was an active issue on the Django site:

You have two options:

  1. Write your own queryset subclass
  2. Add another filter to get the object of your retreived ids

I know how to implement option 2, so here is my approach:

Option #2:

children_ids = ParentModel.objects.filter(name__startswith='A').values_list('child', flat=True)
children = ChildModel.objects.filter(pk__in=children_ids)

Leave a comment