我希望company_name
时unique=True
是company_is_deleted=False
。同样,当company_is_deleted=True
时,company_name
将成为unique=False
。我在使用软删除的地方意味着我只是设置company_is_deleted=True
而不是从数据库表中删除它。
公司型号
class Company(models.Model):
company_name = models.CharField(max_length=20, unique=True) # Here
company_description = models.CharField(max_length=100)
company_address = models.CharField(max_length=100)
company_email = models.EmailField()
company_website = models.URLField()
company_phone = models.CharField(max_length=30)
company_monthly_payment = models.DecimalField(max_digits=5, decimal_places=2)
company_logo = models.ImageField(upload_to='company_logo', default='default_company.png',blank=True, null=True)
company_created = models.DateTimeField(auto_now_add=True)
company_is_deleted = models.BooleanField(default=False)
View.py
class CompanyCreateView(LoginRequiredMixin, generic.CreateView):
model = Company
fields = ['company_name', 'company_description', 'company_email',
'company_website', 'company_address', 'company_phone', 'company_status',
'company_monthly_payment', 'company_logo']
答案 0 :(得分:2)
您可以将该逻辑添加到save
方法中。但请从unique
字段中删除company_name
。
from django.db import IntegrityError
class Company(models.Model):
company_name = models.CharField(max_length=20)
company_description = models.CharField(max_length=100)
company_address = models.CharField(max_length=100)
company_email = models.EmailField()
company_website = models.URLField()
company_phone = models.CharField(max_length=30)
company_monthly_payment = models.DecimalField(max_digits=5, decimal_places=2)
company_logo = models.ImageField(upload_to='company_logo', default='default_company.png',blank=True, null=True)
company_created = models.DateTimeField(auto_now_add=True)
company_is_deleted = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if not self.company_is_deleted and Company.objects.filter(
company_name=self.company_name,
company_is_deleted=False
).exists():
raise IntegrityError
super(Company, self).save(*args, **kwargs)