如何限制用户在db
中保存对象class model_name(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
user = models.ForeignKey(User)
foo = models.CharField(max_length=51)
我想限制 foo 仅限每个用户10个条目
我使用 mysql 作为后端
答案 0 :(得分:4)
你可以做到
class model_name(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
user = models.ForeignKey(User)
foo = models.CharField(max_length=51)
def save(self, *args, **kwargs):
if self.__class__.objects.filter(user=self.user).count()>=10:
return None
return super(model_name, self).save(*args, **kwargs)
#return super().save(*args, **kwargs) python3.x
如果您通过更新forms
方法使用Form.clean
,则可以执行相同的操作
def clean(self):
super(MyForm, self).clean()
if model_name.objects.filter(user=self.cleaned_data['user']).count()>=10:
raise forms.ValidationError("You have exceeded limit.")