Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django- getting a list of foreign key objects

Lets say I have the following models:

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

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

Now, given some filter on ParentModels, I want to retrieve a list of all children models. I have tried:

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

However this returns a list of ChildModel ids, rather than the full objects. Is there a queryset function that will accomplish what I am trying to do or do I need to write an additional filter query using the returned ids? I.e.- instead of:

children => [51L, 53L, 54L]

I want:

children => [<ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>, <ChildModel: ChildModel Object>]
like image 583
MarkD Avatar asked Jul 12 '17 15:07

MarkD


People also ask

Does Django automatically index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

What is ForeignKey in Django?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.

Can a model have two foreign keys Django?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.


2 Answers

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

like image 177
Daniel Roseman Avatar answered Sep 17 '22 21:09

Daniel Roseman


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."

like image 23
rlfrahm Avatar answered Sep 16 '22 21:09

rlfrahm