L
L
Lopus2017-06-08 16:02:03
Django
Lopus, 2017-06-08 16:02:03

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

1 answer(s)
S
Sergey Gornostaev, 2017-06-08
@Lopus

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)

Although, I prefer to limit the possible ForeignKey values ​​in the model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question