如何限制用户在django中保存数据库?

时间:2017-04-28 06:16:58

标签: python mysql django django-models django-mysql

如何限制用户在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 作为后端

1 个答案:

答案 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.")