MikeTeo.net

A Software Developer’s Blog (Wanna Email Me?)

Django Model Reuse

August 21, 2007 By miketeo

I have several models like ”Player”, ”Member” and ”User” which have similar attributes like ”name”, ”email”, ”address”, etc. Being an object-oriented developer, I am inclined to put all the common attributes and properties under a base model like ”BaseUser” and have the other models subclass this base model. However, Django 0.96 is not supporting model inheritance yet, so I have decided to poke into the code to see if I can implement my own workaround.

### Beginning of Code ###
from django.db import models
class BaseUser:
   _meta = models.options.Options(None)
   name = models.CharField('name', maxlength = 255, db_index = True)
   name.set_attributes_from_name('name')
   _meta.add_field(name)
   email = models.CharField('name', maxlength = 255)
   email.set_attributes_from_name('email')
   _meta.add_field(email)
class Player(BaseUser, models.Model):  pass
class Member(BaseUser, models.Model):
   register_date = models.DateTimeField('Register')
### End of Code ###

(Download Code)

After you run python manage.py syncdb, two tables of Player and Member will be created.

  1. Player table will have name and email columns while Member table will have an additional register_date column.
  2. Note that the two tables are independent from each other.

Note that this workaround does not attempt to solve problems associated with model inheritance, i.e. you can’t execute a count() on the base model and expect it to return the total row count of itself plus the child models.

 

  1. Dimitri Gnidash Said,

    Very cool! Thanks for the post. It makes sense since the base object does not inherit from the Model.

Add A Comment