小编Bas*_*abi的帖子

django ValidationError 未在测试中引发,但在 shell 中引发

我在下面定义了一个模型,它在 clean() 方法中调用管理器。

from django.core.exceptions import ValidationError
from django.db import models
from re import sub

class Vessel(models.Model):
    name = models.CharField(max_length=50)
    stripped_name = models.CharField(
        max_length=50, unique=True, null=True, blank=True
    )

    def save(self, *args, **kwargs):
        stripped_name = sub(r'\s+', ' ', str(self.name).upper().strip())
        stripped_name = sub(r'^M[^a-zA-Z]*V\s*', '', stripped_name)
        stripped_name = sub(r'[^\w]', '', str(stripped_name).upper())
        self.stripped_name = stripped_name
        super().save(*args, **kwargs)

    def clean(self):
        stripped_name = sub(r'\s+', ' ', str(self.name).upper().strip())
        stripped_name = sub(r'^M[^a-zA-Z]*V\s*', '', stripped_name)
        stripped_name = sub(r'[^\w]', '', str(stripped_name).upper())
        if Vessel.objects.all().filter(stripped_name = stripped_name).exists():
            return ValidationError("Vessel name exists.")
Run Code Online (Sandbox Code Playgroud)

在新刷新的 …

python django

0
推荐指数
1
解决办法
467
查看次数

标签 统计

django ×1

python ×1