下面的示例主要运用于代码层面的去重处理,不在数据库层面增加唯一键
# 导入依赖
from django.db import models
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import APIException
from django.contrib.auth import get_user_model
User = get_user_model()
# 以书名为例
class Book(models.Model):
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='books',
verbose_name=_('作者')
)
name = models.CharField(null=True, blank=True, max_length=255, verbose_name=_('书名'))
public_time = models.DateField(null=True, blank=True, verbose_name=_('发行时间'))
is_delete = models.BooleanField(default=False, verbose_name=_('是否删除'))
def __str__(self):
return f'{self.name} - {self.author.name} - {self.public_time}'
def clean(self):
if not self.is_delete:
# 检查是否已有相同的书名、作者 且 is_delete=False 的记录
if VersionReviewPlan.objects.filter(
author=self.author,
name=self.name,
public_time=self.public_time,
is_delete=False
).exclude(pk=self.pk).exists():
raise APIException('请检查是否存在相同的书名')
def save(self, *args, **kwargs):
self.clean()
super().save(*args, **kwargs)
class Meta:
verbose_name = _('书名')
verbose_name_plural = _('书名')
标签:name,models,self,校验,Django,表中,delete,书名,verbose
From: https://www.cnblogs.com/wellplayed/p/18623894