Search code examples
djangodjango-modelsdjango-formsdjango-admin

How to filter queryset of a foreignkey field in Django Admin


I have a scenario like this, I have 3 models: Category, Subcategory and Posts.

-Category is One to Many to Subcategory and Subcategory is One to Many to Posts.

My models.py looks like this (minified version).

class Category(models.Model):
    cat=models.CharField(max_length=10)

class SubCategory(models.Model):
    subcat=models.CharField(max_length=10)

class Posts(models.Model):
    cat=models.ForeignKey(Category) 
    subcat=models.ForeignKey(SubCategory) 
    title=models.CharField(max_length=10)

I want to publish a post from admin in which I only want the queryset of subcategories based on selected dropdown from category. Like, if I select Django from dropdown in "Add Posts" section in admin, it should only give me subcategories which were linked to Django(or whatever I choose from dropdown).

I have tried searching a lot and the best I could find is render_change_form. But the problem with render_change_form is, it requires condition for filtration which I don't have as I want the Category from the form itself(based on dropdown selection).

I am not really sure if it's even possible in django.


Solution

  • You have to either write your own custom javascript. So whenever category is selected, subcategory dropdown will be populated based on some ajax hit.

    You may also have a look at django autocomplete light.

    I have used it many times in my project. Your requirement can be achieved using forward argument(send category to subcategory.)

    Hope this helps.