限制每个用户一个约会

问题描述 投票:0回答:2

我正在尝试这样做,因此用户只能预约一个约会。我在这里修改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.')
django django-models django-forms django-rest-framework django-views
2个回答
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
投票

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

def save(self, *args, **kwargs):
    if Appointment.objects.filter(owner=self.owner).exists() and not self.pk:
    ...
© www.soinside.com 2019 - 2024. All rights reserved.