Custom queryset in a list_editable field of Admin changelist

113 views
Skip to first unread message

Daniel França

unread,
Jan 16, 2013, 1:48:09 PM1/16/13
to django...@googlegroups.com
Hello,
I'm using list_editable of a ModelAdmin to allow users change a choicefield right in the changelist view.

Ex:
I've a list

Field1 Field2 ChoiceField
abc     def     foo
ghj     klm     bar

The idea is that ChoiceField is filled according to the field1 and field2 values, so the values filled in "foo" choicefield can be different than in "bar" choicefield.

But to filter this field this way I need to know some field values of the instance I'm pointing.
I'd tried to implement:
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        if db_field.name == 'my_field':
           kwargs['queryset'] = MyNewFiltter

MyNewFilter is a filter based on fields values of the instance itself
But it seems that the formfield_for_foreignkey is not created for a specific instance, so I've no access to instance fields, is there some way to do what I'm thinking about in Admin? If you've any other suggestions to do that please let me know.

Best Regards,
--
Daniel França,

Poorna Shashank

unread,
Nov 15, 2018, 7:28:45 AM11/15/18
to Django users
This has been very old and I had to search for it for a long time. Posting in case some one needs the answer to the same.

So, the way to do this would be to go via the ModelForm route where the querysets for each fields for each instance can be set separately

from django import forms

class MyModelForm(forms.ModelForm):
 
def __init__(self, *args, **kwargs):
   
super(MyModelForm, self).__init__(*args, **kwargs)
    instance
= kwargs['instance']
   
self.fields['my_field'].queryset = MyFieldModel.objects.filter(...)

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
  list_display
= ['foo_field', 'bar_field', 'my_field']
  list_editable
= ('my_field',)
 
 
def get_changelist_form(self, request, **kwargs):
   
return MyModelForm


Reply all
Reply to author
Forward
0 new messages