Django: Defining 'present_company' from 'company_name' ManytoManyField

110 Views Asked by At

I have 2 models, Company and Employee, and defined company history as a ManytoManyField. I am trying to save the present company name of the employee which I get from the company name ManytoManyField. What should be the method to save it?

This is what I tried: I tried to override the save method in Models.

models.py

from django.db import models


class Company(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self) -> str:
        return self.name


class Employee(models.Model):
    name = models.CharField(max_length=100)
    company_name = models.ManyToManyField(Company, blank=True)
    present_company = models.CharField(max_length=100, blank=True)


    def save(self):
        super(Employee, self).save()
        last_index = self.company_name.count()-1
        self.present_company=str(Company.objects.filter(employee__name=self.name)[last_index])
        super(Employee, self).save()
        

    def __str__(self) -> str:
        return self.name

I face two problems with this method:

  1. I add/edit the models from the admin site, when I try to save the models and print the names of the company, it prints out the previous edit and not the latest one.
  2. The order of the companies is not according to the order in which I save the models.

So, what could be the changes in this method, or, some other method to do this job.

1

There are 1 best solutions below

0
On

As @Sahil mentions in comments that he wants the ordering based on employees joined the company.

when you use a Many-to-Many field Django in the backend created a separate table for mapping(through table). you can see this table in DB. now you want the details of Employee joined you can create a table(this table is just same as Many-to-Many field but with extra fields such as joined_in etc.) with details such as follow:

class EmployeeCompnyMap(models.Model):
    employee = models.ForeignKey(
        Employee, on_delete=models.CASCADE, related_name='employee_company_map')
    company = models.ForeignKey(
        Company, on_delete=models.CASCADE, related_name='company_employee_map')
    is_active = models.BooleanField(default=True)
    joined_on = models.DateField(auto_now_add=True)
    resigned_on = models.DateField(blank=True, null=True)

Now if you want second_latest you can do the following in your save model:

last_company = self.employee_company_map.all().order_by('-resigned_on')[1]