在Django中,我有几种类型的模型选择。我愿意在M2M
字段上进行凝乳操作时进行验证吗?
以下是Django模型的示例:
class Employee(models.Model):
TYPE_CHOICES = (
(1, 'OWNER'),
(2, 'STAFF')
)
name = models.CharField(max_length=30, blank=True)
type = models.SmallIntegerField(choices=TYPE_CHOICES, default=2)
staffs = models.ManyToManyField('self', symmetrical=False)
def __str__(self):
return f'{self.id}: {self.name}: {self.type}'
def clean(self):
"""How to validate if adding staff is of type `STAFF`?"""
"""would like to check type of child object here?"""
pass
在为所有者对象添加人员时如何验证所有人员对象,以便所有者只能将子对象作为人员?
staff = Employee.objects.create(name='emp1')
owner = Employee.objects.create(name='emp1', type=1)
owner.staff.add(staff)