Search code examples
djangodjango-modelsdjango-viewsdjango-querysetdjango-orm

Django ForeignKey reverse relationship


I have 2 models, A parent and child model. I am trying to call the child model from the parent model

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

class ChildClass(models.Model):
    name = models.CharField(...)
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name=child_class)

If i want to refer to the Parent class i know i can use child class

new=ChildClass.objects.all then new.parent.name will give me parent name

The problem comes when i want to call the child class through the ManyToOne relationship. I don't know how to build my queryset.

I haven't tried anything cos i have never faced this problem and i couldn't find answer about it here


Solution

  • What you're looking for is the _set magic that Django automatically adds to your Parent model. See here

    But, bear in mind this wont get just one child from your parent, because your parent might have many children.

    However, in your case, something like this should give you all of the children of the parent.

    parent = Parent.objects.first()
    children = parent.childclass_set.all()