Reverse self referencing foreign key in Django
Asked Answered
G

1

5

Sorry if this is a stupid question, but I'm a bit of a Django newbie and can't find the answer.

I have an Order model with a self-referencing field:

source = models.ForeignKey(
    'self',
    help_text = "[redacted]",
    verbose_name = "Source Order",
    blank = True,
    null = True,
)

While this works fine if I have an Order and I want to know its source, I also need to get a list of an Order's "children" - that is, a list of Orders for which this Order is the source. Does this need to be done through filter()s or is there a nice, Django-y way to do it?

Guidotti answered 15/2, 2013 at 18:52 Comment(0)
K
7

If you have an Order object, you can use the reverse relationship:

child_orders = my_order.order_set.all()

You may want to give the source field a more descriptive related_name value which would be used in place of order_set above.

Killigrew answered 15/2, 2013 at 19:9 Comment(1)
That did it, and it sure sounds like a Right Answer(tm) too. Thank you!Guidotti

© 2022 - 2024 — McMap. All rights reserved.