【问题标题】:Limiting one appointment per user限制每个用户一次约会
【发布时间】:2018-06-10 05:35:52
【问题描述】:

我正在努力让用户只能安排一次约会。这里我正在修改保存方法。我想弄清楚的是如何查看该用户是否已经有约会。

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


    【解决方案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.
    

    【讨论】:

    • 啊,是的,这听起来绝对是正确的做法!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 1970-01-01
      • 2023-04-06
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多