Reputation: 75
I want to construct a binary tree like structure(using reverse relation)
an employee with report_to field null is top of the tree(A grade), using reverse serializer I can get their controlled employee list(B grade). but if the B grade employee is controlling some employees then I have to reverse relate that employee list(C grade). some B grade employee may or may not have employee reporting to them. then C grade employee may or may not have employee reporting to them and so on the tree grows till the last employee.
I have an employee table and job_info table
class employee(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
class job_info(models.Model):
employeeid = models.OneToOneField(employee, on_delete = models.CASCADE)
report_to = models.ForeignKey(employee, on_delete = models.SET_NULL,related_name = "supervisor", null = True)
if I need to find a limited amount of reverse serializer, I can write the required amount of reverse relation serializer. but in my case, the tree maybe (0 grade) to (N grade). so how do I write a serializer that can handle N number of reverse serializer
Upvotes: 0
Views: 43
Reputation: 488
Quick way to think of this would be SerializerMethodField. Something like:
class Employee(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
class JobInfo(models.Model):
employee = models.OneToOneField(Employee, related_name='get_job_info')
supervisor = models.ForeignKey(Employee, related_name='get_sub_employees_info')
class JobTreeSerializer(serializers.ModelSerializer):
class Meta:
model = JobInfo
fields = ('employee', 'sub_employees')
sub_employees = serializers.SerializerMethodField()
def get_sub_employees(self, job_info):
return __class__(job_info.employee.get_sub_employees_info.all(), many=True).data
Note __class__ refers JobTreeSerializer, it would be like nesting the same serializer in itself.
Upvotes: 2