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>]
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
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.
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.
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.)
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With