How do I restrict foreign keys choices to related objects only in django

Posted by Jeff Mc on Stack Overflow See other posts from Stack Overflow or by Jeff Mc
Published on 2008-10-24T03:52:50Z Indexed on 2011/01/11 1:54 UTC
Read the original article Hit count: 211

Filed under:
|
|

I have a two way foreign relation similar to the following

class Parent(models.Model):
  name = models.CharField(max_length=255)
  favoritechild = models.ForeignKey("Child", blank=True, null=True)

class Child(models.Model):
  name = models.CharField(max_length=255)
  myparent = models.ForeignKey(Parent)

How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried

class Parent(models.Model):
  name = models.CharField(max_length=255)
  favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"})

but that causes the admin interface to not list any children.

© Stack Overflow or respective owner

Related posts about python

Related posts about django