There is an Account model in which there is a CharField account_type .

How to make the ForeignKey(account) field in another model so that in the admin area you can only select those accounts that have account_type == "user" ?

    2 answers 2

    In this case, it is better to use limit_choices_to

     class OtherModel(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, limit_choices_to={'account_type': 'user'}, ) 

    https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

    • If the task is not to limit the field values ​​only in the admin panel. - Sergey Gornostaev
    • @Sergey Gornostaev, it's hard to imagine a situation where you need to restrict the admin panel, without limiting the custom ModelForm, I think in 99% of cases limit_choices_to is fine. - Basalex
    • one
      I think so too :) - Sergey Gornostaev
    • And the forms in the project are not used, this is a backend built entirely on json requests, but in this particular case - the field is supposed to be changed from the admin panel only. :) - Paul Shishmarev

    The documentation has the answer to this:

     class SomeModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "account": kwargs["queryset"] = Account.objects.filter(account_type="user") return super().formfield_for_foreignkey(db_field, request, **kwargs)