I have the following models:
class Client(BaseModel): #other fields engineers = models.ManyToManyField(Engineer, null = True, blank = True, related_name='clients') class OrganizationMember(MPTTModel): designation = models.CharField(max_length = 100, blank = True) user = models.OneToOneField(User, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL)
Now I would like to get
all engineers of a
client instance and check if each
engineer has an
organizationmember instance or not.
Then if they belong to some organization then I should
get_ancestors of that
organizationmember and then the users.
If they do not have any
organizationmember then just get the user of that engineer instance.
For this I have written a method in
Client model as below:
class Client(BaseModel): def get_users_from_engineers(self): users_in_organization = () users_outside_organization = () engineers = self.engineers.all() if engineers: for engineer in engineers: user = engineer.user if hasattr(user, "organizationmember"): users_in_organization += (orgmember.user for orgmember in user.organizationmember.get_ancestors(include_self=True)) else: users_outside_organization.append(user)
Now this code is working correctly but I am sure that I can use django filters here instead of two
for loops and optimize this code. But I do not know how.
can be used to get all the
organizationmembers of the
engineers of that particular
client instance. But I need the users of those
Also if I use
get_ancestors on multiple engineers then more than one engineer might have the same ancestor thereby adding the same person more than once in the
users_in_organization list. How can I rectify this if I use django filters?
Note: This is my first question in codereview. I do not know if this question should be asked here or in stackoverflow since I already have a working code. Anyway I have asked the same question in stackoverflow also. Please feel free to correct me regarding the same.