[Answered ]-Can I filter choices for Django models.ForeignKey?

1👍

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

class Assignment(models.Model):
    driver = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        limit_choices_to={'is_driver': True}
    )
    puv = models.ForeignKey(Puv, on_delete=models.CASCADE)
    assignment_date = models.DateField(auto_now_add=True)

This will not be enforced by the database, but will be checked by a ModelForm, and by the ModelAdmin.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment