Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 5 months ago by PlanetaryProbe222

How can I restrict ForeignKey choices using a reverse relationship in Django admin?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

Hello there,

I have a basic model structure where the Parent model includes a ForeignKey field named default_child that uses limit_choices_to to filter choices based on a reverse relationship from the Child model. Here's the code:

PYTHON
class Parent(models.Model): name = models.CharField(... default_child = models.ForeignKey( to="Child", null=True, on_delete=models.SET_NULL, limit_choices_to=models.Q(parent_id=models.F("id")), related_name="+", ) class Child(models.Model): name = models.CharField(... parent = models.ForeignKey( to="Parent", related_name="children", )

I was expecting the default_child field in the admin panel’s change page to be populated with suitable choices, but it remains empty. Is there an alternative method to achieve this filtering?

1

Comments 0

Answers 0

Views 59

0 Answers

Discussion

No comments yet.