Updating mixin subclassed instances

19 views
Skip to first unread message

Radek Svarz

unread,
Oct 31, 2016, 3:03:37 PM10/31/16
to Django users
Hi,

I am using my custom permission mixin on several of my apps's models (not all).

For the case when I need to merge from the "old - context" permission to the "new - context" permission I want to have function which changes the corresponding permission reference attribute in all models, which subclassed this mixin.

How do I know which models subclassed this permission mixin and that they have the inherited permission reference attribute?

In fact I want to have such function in my mixin:

@classmethod
def merge_to(cls, from_perm_context, to_perm_context):

    perm_context_models = []  # How to get this?

    try:
        with transaction.atomic():
            for model in perm_context_models:
                model.objects.filter(
                    perm_context=from_perm_context,
                ).update(perm_context=to_perm_context)
    except IntegrityError as e:  # or DatabaseError
        raise e



Thanks, 

Radek

Vijay Khemlani

unread,
Nov 1, 2016, 2:20:18 PM11/1/16
to django...@googlegroups.com
You could use a metaclass to keep track of all the classes that inherit from a given one, in a pure Python way it would be something like this

class PluginMeta(type):
    # we use __init__ rather than __new__ here because we want
    # to modify attributes of the class *after* they have been
    # created
    def __init__(cls, name, bases, dct):
        if not hasattr(cls, 'registry'):
            # this is the base class.  Create an empty registry
            cls.registry = {}
        else:
            # this is a derived class.  Add cls to the registry
            interface_id = name.lower()
            cls.registry[interface_id] = cls
        super(PluginMeta, cls).__init__(name, bases, dct)

class Plugin(object):
    __metaclass__ = PluginMeta


So, all the classes that inherit from Plugin are stored in Plugin.registry. Not sure if it works for mixins though.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/576474f7-dace-4986-b121-0eb2e5428122%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Radek Svarz

unread,
Nov 2, 2016, 4:29:32 AM11/2/16
to Django users
@Vijay, thanks. I also had a similar idea, but I was surprised it was not somewhere already implemented. 


It works (Python 3.3, Django 1.8) ;)

Thx, R
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages