限制每个用户一个约会

时间:2017-12-29 20:55:33

标签: django django-models django-forms django-rest-framework django-views

我试图制作它,以便用户只能安排一次约会。我在这里修改save方法。我想弄清楚的是如何查看该用户是否已经预约。

def save(self, *args, **kwargs):
    if Appointment.objects.filter(owner=user_pk).exists() and not self.pk:
        # if you'll not check for self.pk
        # then error will also raised in update of exists model
        raise ValidationError('You have already scheduled an appointment.')
    return super(Appointment, self).save(*args, **kwargs)

在我的views.py中,如果已经存在与该用户的约会,我已经有了一些会引发错误的内容。但我认为这还不够,模型层面应该有一些东西。

appointments = Appointment.objects.filter(owner=request.user)
    if appointments.exists():
        raise PermissionDenied('You have already scheduled an appointment.')

2 个答案:

答案 0 :(得分:1)

我会将数据库关系更改为OneToOneField,而不是让您的视图处理该逻辑。让该字段可以为空,因此您可以依靠django的db模块来维护该字段的关系完整性

如源代码所述:

A OneToOneField is essentially the same as a ForeignKey, with the exception
that it always carries a "unique" constraint with it and the reverse
relation always returns the object pointed to (since there will only ever
be one), rather than returning a list.

答案 1 :(得分:1)

self对象的owner属性设置为当前用户,因此您可以使用self.owner来访问它:

def save(self, *args, **kwargs):
    if Appointment.objects.filter(owner=self.owner).exists() and not self.pk:
    ...