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

24👍

You can use a subquery with __in:

Child.objects.filter(parent__in=Parent.objects.filter(name__startswith='A'))

(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.)

6👍

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:

ParentModel.childmodel_set.all()

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

5👍

This one was an active issue on the Django site:
https://code.djangoproject.com/ticket/8144

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