Login

ModelMixin

Author:
eallik
Posted:
November 4, 2010
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.