how to filter the model we use in model.ForeignKey in django

Viewed 19

I have model in django that has some instaces in itself:

class Account(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=50, unique=True)
    #some instances...
    is_agent = models.BooleanField(default=False)
    agent = models.ForeignKey("self", verbose_name=('agent'), on_delete=models.SET_NULL, blank=True, null=True)

i want to pass only Accounts objects that is_agent set to True in my model.ForeignKey() method. i don't want to use inheritence for some reasons.

2 Answers

You can use the limit_choices_to=… parameter [Django-doc] for this:

class Account(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=50, unique=True)
    is_agent = models.BooleanField(default=False)
    agent = models.ForeignKey(
        'self',
        verbose_name=('agent'),
        on_delete=models.SET_NULL,
        blank=True,
        null=True,
        limit_choices_to={'is_agent': True}
    )

i've found the solution:

agent = models.ForeignKey("self", verbose_name=('agent'),limit_choices_to={'is_agent': True}, on_delete=models.SET_NULL, blank=True, null=True)

we should use limit_choices_to option

Related