edit- updated models.py models.py:
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Department(models.Model):
departmentName = models.CharField(max_length=100)
def __str__(self):
return self.departmentName
class Designation(models.Model):
designationName = models.CharField(max_length=100, null=True)
def __str__(self):
return self.designationName
class Employee(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True, blank=False)
department = models.ManyToManyField(Department, blank=True)
designation = models.ForeignKey(Designation, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.name
def departments(self):
return ",".join([d.departmentName for d in self.department.all()])
#Using post receiver signal as suggested by @Daniel in answer and comments
@receiver(post_save, sender=Employee, dispatch_uid='set_department')
def SetDefaultDeparment(**kwargs):
employee = kwargs['instance']
if not employee.department.all():
resource_pool = Department.objects.get(departmentName="RP")
employee.department.add(resource_pool)
employee.save()
My query/requirement: Employee and Department are linked by M2M. I set blank=True to overcome the form validation of no department being chosen. (null=True doesn't seem to be working with M2M)
Let's say,
scenario 1: while creating a new Emp, if there is no department provided then it should set to RP(Resource pool) by default.
scenario 2: An existing Emp is from the HR department; assuming for some reason the HR dept is being deleted or Emp is being kicked out, now that Emp has no department linked to it, it should move to RP(Resource pool) by default!!
How to arrange the default department- RP in Django such that both the scenarios are passing!?
Thanks in advance :)
Dueces