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

How limit a user to save database in django?

如何限制用户在数据库中保存对象

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 作为后端

你可以做到

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