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" ?
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'}, ) 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) Source: https://ru.stackoverflow.com/questions/854214/
All Articles