Login

ModelMixin

Author:
eallik
Posted:
November 4, 2010
Language:
Python
Version:
Not specified
Tags:
mixin metaclass util metaprogramming
Score:
2 (after 2 ratings)

Enables convenient adding of fields, methods and properties to Django models.

Instead of:

User.add_to_class('foo', models.CharField(...)
User.add_to_class('bar', models.IntegerField(...)

you can write:

class UserMixin(ModelMixin):
    model = User

    foo = models.CharField(...)
    bar = models.IntegerField(...)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
##############
#  utils.py  #
##############

class MixinType(type):
    def __new__(cls, name, bases, dct):
        ret = type.__new__(cls, name, bases, dct)

        if name != 'ModelMixin':
            assert 'model' in dct
            model = dct.pop('model')

            for k, v in dct.iteritems():
                if k not in ModelMixin.__dict__:
                    model.add_to_class(k, v)

        return ret


class ModelMixin(object):
    __metaclass__ = MixinType


###############
#  models.py  #
###############

class UserMixin(ModelMixin):
    model = User

    @property
    def foobar(user):
        try:
            return user.foobar_set.get()
        except Foobar.DoesNotExist:
            return None

    @property
    def is_boss(user):
        return user.foobar is not None

    def __unicode__(user):
        try:
            profile = user.get_profile()
            if profile.full_name:
                return profile.full_name

        except UserProfile.DoesNotExist:
            pass

        full_name = (u'%s %s' % (user.first_name, user.last_name)).strip()
        if full_name:
            return full_name

        return user.username

    def get_absolute_url(user):
        return reverse('localsite_user_detail', kwargs=dict(username=user.username))

More like this

  1. Automatic Manager Choice Filters by nipuL 6 years, 6 months ago
  2. Get derived model instance by werehuman 1 year, 10 months ago
  3. Flatpage Suggester Template tag for 404 templates by bradmontgomery 5 years, 6 months ago
  4. Humanize lists of strings in templates by ChipX86 8 years, 1 month ago
  5. ReadOnlyFieldsMixin by luzfcb 2 weeks, 6 days ago

Comments

Please login first before commenting.