我有一个模型, unique_together 参数不起作用。原因是大多数时候“client_repr”变量是在 save() 方法上设置的。如果有人使用相同的 ('client_repr', 'task_type'...) 组合创建任务,模型将不会检测到它,因为在 save() 方法结束之前“client_repr”值为 null。
如何在 save() 方法中调用唯一约束验证?
class Task(models.Model):
client = models.ForeignKey(Client, related_name = 'tasks', on_delete = models.CASCADE)
b_client = models.ForeignKey(BClient, related_name = 'tasks', on_delete = models.CASCADE, null = True, blank = True)
client_repr = models.CharField(max_length = 100, null = True, blank = True)
task_type = models.CharField(max_length = 100)
task_description = models.CharField(max_length = 100)
department = models.ForeignKey(Department, related_name = 'tasks', on_delete = models.CASCADE)
extra_fields = models.ManyToManyField(ExtraField, blank = True)
spot = models.BooleanField(default = False)
class Meta:
unique_together = (('client_repr', 'task_type', 'task_description', 'department'), )
def __str__(self):
return ' | '.join([f'{self.client_repr}', f'{self.task_description}', f'{self.task_type}'])
def save(self, *args, **kwargs):
if not self.b_client:
self.client_repr = str(self.client)
else:
self.client_repr = str(self.b_client)
super().save(*args, **kwargs)
我知道我可以进行搜索(例如: if Task.objects.get(...): ),但这是最 django-pythonic 的方式吗?
米脂
相关分类