Answer the question
In order to leave comments, you need to log in
How can I filter the list in the admin for ForeignKey?
There are models: Category, Articles, News
Articles and News have a category=ForeignKey(Category) field
In the admin panel, when adding an article or news, you can select a category from the list. I would like to filter the list of possible categories for News by some parameter. For articles, respectively, leave everything as it is.
I suspect that for News.admin you can override some method and somehow slip your own sampling algorithm.
Answer the question
In order to leave comments, you need to log in
Override ModelAdmin.formfield_for_foreignkey :
class NewsAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "category":
kwargs["queryset"] = Category.objects.filter(some_parameter=some_value)
return super(NewsAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question