如何在Django中设置ManyToManyField的默认值



编辑-更新的模型.py型号.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()

我的查询/需求:员工和部门通过M2M链接。我设置为空=True以克服没有选择部门的表单验证。(null=True似乎不适用于M2M(

比方说,

场景1:在创建新Emp时,如果没有提供部门,则默认情况下应设置为RP(资源池(。

场景2:现有的Emp来自人力资源部门;假设由于某种原因人力资源部门被删除或Emp被踢出,现在Emp没有链接到它的部门,它应该默认移动到RP(资源池(!!

如何在Django中安排默认的department-RP,使两种场景都通过!?

提前感谢:(

应付款

正如这里所建议的,在django中设置ManyToMany字段默认值的正确方法是,您有几个选项。

以下是如何通过覆盖保存方法来做到这一点:

class Employee(models.Model):
...

def save(self): 
# set department if field is empty:        
if not self.department.all(): 
# get the resource pool department:
resource_pool = Department.objects.get(name='Resource Pool')
# add to instance:
self.department.add(resource_pool)

super(Employee, self).save(*args, **kwargs)

以下是如何使用postrongave接收器:

from django.db.models.signals import post_save
from django.dispatch import receiver
# this decorator will execute the function after an Employee is saved:
@receiver(post_save, sender=Employee, dispatch_uid='set_department')
def SetDefaultDeparment(**kwargs):

''' sets a default department for an Employee where needed '''

# unpack kwargs:
employee = kwargs['instance']
# set department if field is empty:        
if not employee.department.all(): 
# get the resource pool department:
resource_pool = Department.objects.get(name='Resource Pool')
# add to instance:
employee.department.add(resource_pool)
employee.save()

相关内容

  • 没有找到相关文章

最新更新