Asked 11 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.
Asked 11 months ago by PlanetaryProbe222
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:
PYTHONclass 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?
Comments 0
•Answers 0
•Views 91
No comments yet.