简体   繁体   中英

Limiting Foreign Key Choices in Django Admin *rows*

I have two Django Models X and Y that both have a "type" field, and Y is a ForeignKey for X. When displaying the list (rows) of X, Django automatically shows me a choice box for Y, including all possible instances of Y. However, I want to limit the ForeignKey choices to those that have the "type" set the same as the current object.

I have looked at plenty of related questions on this, and have learned that one way of accomplishing this is to override the formfield_for_foreignkey method of ModelAdmin , and because I need to know the type of the current object, I also need to override get_form and add a reference to the current object to the request.

This works when editing the form for an individual instance, but does NOT work when loading the admin's table-based view for all instances of the Model. Apparently it calls formfield_for_foreignkey , but not get_form , so the object reference that I'm looking for doesn't exist. Any thoughts on how to make this work?

limit_choices_to is what you are looking for. It ensures what you want to do at model level rather than in form level. This way the queryset for your forms will be already filtered (no need to override the formfield_for_foreignkey anymore).

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