Sat 3 May 2008
Into trunk merged queryset-refactor branch, that makes it easy to inherit django-models. It has been known to all. But inheritance is not the only alternative, it can be also used Monkey patching.
The main idea is that Monkey patching also lets you add not only the fields, but also the functions.
For example, so will be added in the model User the field OpenID, and the additional function, that returns the nickname, if there is no name
additional tables are not created
in the work with the model will be used standard instruments of django
The main idea is that Monkey patching also lets you add not only the fields, but also the functions.
For example, so will be added in the model User the field OpenID, and the additional function, that returns the nickname, if there is no name
from django.contrib.auth.models import User
User.add_to_class('openid', models.CharField(max_length=250,blank=True))
def get_user_name(self):
if self.first_name or self.last_name:
return self.first_name + " " + self.last_name
return self.username
User.add_to_class("get_user_name",get_user_name)
The main benefits of the method:additional tables are not created
in the work with the model will be used standard instruments of django
English
Deutsch
Русский
(12 votes, average: 4.7 out of 5)

May 4th, 2008 at 10:24 a.m.
Но при этом нужно вручную создавать в БД поле для 'openid'?
P.S. Можно тут как-то подписаться на комменты?
May 4th, 2008 at 12:50 p.m.
Вручную создавать, конечно, не надо, все поля автоматически создаются при первом syncdb. Если модель User уже есть, то конечно syncdb тут не поможет и тогда путь - вручную.
Пы.Сы. Пока подписки нет, все руки не доберутся :(
Скоро собираюсь кардинально переделать движок...
May 6th, 2008 at 3:14 p.m.
Подскажите, как сделать так, что бы эти поля были доступны для редактирование через админку?
May 6th, 2008 at 4:54 p.m.
Например, так (там же, просто дописать ниже):
User._meta.admin.fields += (('Custom Fields', {'fields': ('openid',)}),)
User._meta.admin.list_display += ('openid',)
May 6th, 2008 at 5:55 p.m.
Спасибо )) Но обнаружил странное поведение системы:
код:
from django.contrib.auth.models import User
User.add_to_class('department',models.CharField(max_length=250,blank=True))
User.add_to_class('position',models.CharField(max_length=250,blank=True))
User._meta.admin.fields += (('Custom', {'fields': ('department','position',)}),)
User._meta.admin.list_display += ('department','position',)
в итоге два поля добавились дважды в таблицу вывода http://localhost:8000/admin/auth/user/ и так же дважды появились при редактировании пользователя
May 6th, 2008 at 6:23 p.m.
1) используется SVN?
2) в каком файле это добавление? нет ли такого же дубликата еще в других местах? этот код надо прописывать только в одном (любом) models.py. Может проблема в этом...
May 7th, 2008 at 1:02 p.m.
1. да свн билд 7519
2. все так и сделано в models.py один раз
May 7th, 2008 at 4:02 p.m.
У меня не дублируются поля, вставил сейчас твой код, тоже все отработало как надо, странно, может, что лишнее в остальном коде... когда не видишь, трудно что определенное сказать....
May 13th, 2008 at 3:51 p.m.
Сорри, чт пишу в камменте, но не нашел нигде на сайте инфы. А как с вами связаться? Есть вопрос на тему статьи про Django.
May 13th, 2008 at 4:07 p.m.
есть вверху форма Contact, или на мыло alrond @ gmail [.] com
May 19th, 2008 at 12:55 a.m.
вообще-то и раньше можно было свои методы к чужим моделям прикручивать:
def _get_userdomain(self):
domain = Site.objects.get_current().domain
return unicode('http://%s.%s' % (self.username, domain))
User.userdomain = property(_get_userdomain)
October 14th, 2010 at 4:04 p.m.
Hello,
This is in fact a pretty interesting solution that I have used to make a model patcher. See this blog post :
http://www.ravelsoft.com/blog/2010/pa...