Sreekanth Reddy Balne
Sreekanth Reddy Balne

Reputation: 3424

How to get all inherited objects of a particular object of a model in django

I have these models:

class User(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)

class Manager(User):
    experience_in_field_in_years = models.DecimalField(max_digits=5, decimal_places=2)

class SalesPerson(User):
    current_hourly_rate = models.DecimalField(max_digits=5, decimal_places=2)
    work_timings = models.CharField(max_length=255)

class Role(models.Model):
    name = models.CharField(max_length=255)

class UserRole(models.Model):
    user = models.ForeignKey("User", related_name="user_roles", on_delete = models.CASCADE)

Observer that User model is inherited by Manager, SalesPerson: there is a parent_link being generated as user_ptr_id to User table.

Now, whenever I create a manager/sales_person, a user is auto created.

A user can be both manager and sales_person. So, How to find/group a user with its child models? If I get a user from User, I need a way to know that he is a manager cum sales_person or only manager.

manager = Manager.objects.get(pk=2) #here 2 is actually the user id-> User model
manager.name #white
manager.experience_in_field_in_years #5

The above works. But,

user = User.objects.get(pk=2)
user.name #white
user.experience_in_field_in_years #error!! doesn't work. I want this to work.

Another query Should I use the Role, UserRole models? since I am already creating separate models for the respective roles?

Upvotes: 0

Views: 1131

Answers (2)

Raphaël Khan
Raphaël Khan

Reputation: 86

I suggest you take a look at the django extension polymorphic-models https://django-polymorphic.readthedocs.io/en/stable/

from polymorphic.models import PolymorphicModel

class User(PolymorphicModel):
    name = models.CharField(max_length=255)
    email = models.EmailField(max_length=255)

class Manager(User):
    experience_in_field_in_years = models.DecimalField(max_digits=5, decimal_places=2)

class SalesPerson(User):
    current_hourly_rate = models.DecimalField(max_digits=5, decimal_places=2)
    work_timings = models.CharField(max_length=255)

Then user in the following code is a Manager instance Manager.objects.create(name='manager') user = User.objects.get(name='manager')

Upvotes: 1

Marcell Erasmus
Marcell Erasmus

Reputation: 914

You can check if the User object has a manager or salesperson attribute:

if hasattr(user, 'manager'):
    # then object is a manager instance

if hasattr(user, 'salesperson'):
    # then object is a salesperson instance

Upvotes: 3

Related Questions