Changes between Initial Version and Version 1 of ModelInheritance


Ignore:
Timestamp:
Aug 24, 2005, 1:32:19 PM (19 years ago)
Author:
Adam Endicott <leftwing17@…>
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ModelInheritance

    v1 v1  
     1This is a work in progress, I just discovered this a couple of hours ago.
     2
     3There's an undocumented (as of this writing) way to do model inheritance. The magic involves defining {{{ add_fields }}}, {{{ ignore_fields }}}, and {{{ replaces_module }}}. Here's an example of extending auth.User:
     4
     5{{{
     6from django.core import meta
     7from django.models import auth
     8
     9class User(auth.User):
     10    add_fields = (
     11         meta.ForeignKey(Company),
     12         meta.PhoneNumberField('phone', blank=True),
     13         meta.SmallIntegerField('extension', blank=True, null=True),
     14         meta.CharField('position', maxlength=255, blank=True),
     15        )
     16    replaces_module = 'auth.users'
     17
     18    admin = meta.Admin(
     19        fields = (
     20            (None, {'fields': ('username', 'password_md5')}),
     21            ('Personal info', {'fields': ('first_name', 'last_name', 'email')}),
     22            ('Extra info', {'fields': ('company_id', 'phone', 'extension', 'position')}),
     23            ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'user_permissions')}),
     24            ('Important dates', {'fields': ('last_login', 'date_joined')}),
     25            ('Groups', {'fields': ('groups',)}),
     26        ),
     27        list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff'),
     28        list_filter = ('is_staff', 'is_superuser'),
     29        search_fields = ('username', 'first_name', 'last_name', 'email'),
     30    )
     31}}}
     32
     33This model will have everything in auth.User, as well as all the fields in add_fields. Since I defined replaces_module as auth.users, it actually replaces the auth.User model. If replaces_module was not defined, it would just be a separate users model, though it would still have all the same fields.
     34
     35I haven't tried ignore_fields yet, but I presume that it will cause specified fields to be removed from the model. It looks like it takes a list of field names.
     36
     37Notice also that I've redefined admin above to include the extra fields. Be sure to do that if you want them to show up in the admin interface.
     38
     39== Gotchas ==
     40Replacing auth.User in this way breaks createsuperuser. You'll have to add an inital superuser to the database manually.
     41
     42If your other model classes have foreign, or many to many relationships with User, make sure its to your redefined User class, not auth.User, otherwise the user objects will not have the expected get_otherthing() methods.
Back to Top