Mixin Question for ModelAdmin

I override the ModelAdmin method this way:

def response_change(self, request, obj):
    # alter redirect location if 'source' is found in GET
    response = super(JobOptions, self).response_change(request, obj)
    source = request.GET.get('source', None)
    if source:
        response['location'] = source
    return response

Instead of repeating this on each model, I would like to make it a mix.

If I do this:

def RedirectMixin(admin.ModelAdmin)

and then:

def MyModel(admin.ModelAdmin, RedirectMixin)

then I get a MRO error.

However, if RedirectMixin does not inherit from admin.ModelAdmin, then the method will not be called.

Another problem is how to generalize the call to super (), so it does not have hard coding in the superclass.

+3
source share
1 answer

First, I assume that you mean class, not defyour examples.

In any case, the correct way to use Mixin is to use it in the list of classes for inheritance first. So:

class RedirectMixin(object):

and

class MyModelAdmin(RedirectMixin, admin.ModelAdmin):

, Python , , .

, - . :

return super(MyModelAdmin, self).__init__(self, *args, **kwargs)

- .

, mixin super. :

In [1]: class BaseClass(object):
   ...:     def my_function(self):
   ...:         print 'base my_function'
   ...:     

In [2]: class Mixin(object):
   ...:     def my_function(self):
   ...:         print 'mixin my_function'
   ...:         super(Mixin, self).my_function()
   ...: 

In [3]: class MyDerivedClass(Mixin, BaseClass):
   ...:     pass
   ...: 

, my_function, MRO , , Mixin BaseClass:

In [4]: m=MyDerivedClass()

In [5]: m.my_function()
mixin my_function
base my_function

, Mixin object - , , .

+11

All Articles