内部仅使用模型的模型验证

时间:2017-06-28 09:12:12

标签: django django-models django-orm

我有一个模型只在视图中由python内部使用。没有涉及的形式。看起来像这样

class ShareLink(models.Model):

    from_share = models.ForeignKey(Share, on_delete=models.CASCADE, related_name='from_share')
    to_share = models.ForeignKey(Share, on_delete=models.CASCADE, related_name='to_share')

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    creator = models.ForeignKey(settings.AUTH_USER_MODEL)
    active = models.BooleanField(default=True)

    mode = models.PositiveSmallIntegerField(choices=SHARE_LINK_MODE_CHOICES, default=1)

    class Meta:

        unique_together = ('from_share', 'to_share', 'mode', 'active')

    def clean(self):
        ret = super(ShareLink, self).clean()
        return ret

根据colum模式,我有一些限制。例如,创建者必须是from_share的创建者,依此类推。所以基本上会在模型的clean()中做些什么。但只有在涉及ModelForm时才会调用此方法。但我没有,因为这个模型只用于internaly。验证我的模型的最佳方法是什么?任何建议

1 个答案:

答案 0 :(得分:1)

在模型中实现clean()方法之后,您可以在保存实例以执行验证之前在视图中调用full_clean()方法(请参阅docs):

sharelink = ShareLink()
try:
    sharelink.full_clean()
except ValidationError as e:
    # Do something based on the errors contained in e.message_dict.
    # Display them to a user, or handle them programmatically.
    pass
sharelink.save()