如何不显示 created_by 字段,而是使用当前用户保持 unique_together 规则自动填充它?

How not to display the created_by field but auto-populate it with the current user keeping the unique_together rule?

我的模型假设每个用户(假设是医生)都可以有自己的患者。因此,Patient 模型为当前登录的用户提供了一个 'created_by' 字段。每个医生 (i.e.User) 应该只有一个名字和名字相同的病人 (例如 John Smith),但是不同的医生 (即其他用户) 可以再次有一个病人叫例如约翰·史密斯。因此,我将 first_name、last_name、created_by 这三个字段标记为 unique_together。

class Patient(models.Model):
     first_name = models.CharField(max_length = 30)
     last_name = models.CharField(max_length = 30)
     created_by = models.ForeignKey(User, blank=True)

    class Meta:
         unique_together = (("created_by","first_name", "last_name"),)

我想要实现的是 'created_by' 字段不应出现在表单中,而应该是自动的-populated.Here 的 ModelForm:

class PatientForm(ModelForm):

    class Meta:
        model=Patient
        fields = '__all__'

    def save(self,request):
        obj = super(PatientForm, self).save(commit = False)
        obj.created_by = request.user
        obj.save()

    def clean(self):
        cleaned_data = super(PatientForm, self).clean()

        first_name = cleaned_data.get('first_name')
        last_name = cleaned_data.get('last_name')
        created_by = cleaned_data.get('created_by')

        if Patient.objects.filter(first_name = first_name, last_name = last_name, created_by = created_by).exists():
            raise ValidationError('This name already exists!')
        else:
            return cleaned_data

问题在于:如您所见,ModelForm 包含 'created_by' 字段。如果我使用 ModelForm 排除它,unique_together 验证将不起作用。如果我不在模板中显示 'created_by' 字段,它将在 form.is_valid() 验证步骤期间在视图中失败。

如何不显示 created_by 字段,而是使用当前用户保持 unique_together 规则自动填充它?

Django 已经 validates the uniqueness 为您准备了您的模型,您无需自己动手。诀窍是确保在验证模型之前设置 created_by 字段,即如果您要创建新患者:

p = Patient(created_by=request.user)
form = PatientForm(data=request.POST or None, instance=p)

不需要将 created_by 字段添加到表单中 - 除非当前用户只是一个默认值并且医生可以将另一个医生的患者添加到系统中。在这两种情况下,Django 本身都会检查您的 Patient 是否遵循 unique_together 约束。