简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM