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:
- 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.
- 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.
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 asjoined_in
etc.) with details such as follow:Now if you want
second_latest
you can do the following in your save model: