Question

Im just getting in to both Python and Django, so pardon my ignorance.

In building out my models I've decided to go with user extension rather than replacement. Just seems simpler and I'm still new. What I've found is that an abstract will work really well for generic info, address phone etc, however I also need multiple models for differing info (employee v client for ex). So my question is:

Can and abstract extend the user, then be used to as a base for each model?

code:

class Common(models.Model):
    user = models.OneToOneField(User)
    #other proprerties addr, ph etc

    Class Meta:
       abstract = true

class Employee(Common):
    reportsTo = models.OneToOneField(User)
    #timeOff, title, dept, etc.

Is that doable, or would another method work better?

Was it helpful?

Solution

Yes, this will work fine, you can also store any other common attributes in the base class.

You may also want to use InheritanceManager provided as part of django-model-utils, this allows you to perform a query on the Common base class and retrieve a collection where all the objects are instances of Employee or Client using:

Common.objects.all().select_subclasses()

Otherwise all the objects will only contain the link to the User objects. For a more complete example see: django - Get a set of objects from different models field names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top