0

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

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

4

1 回答 1

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.")
于 2017-04-28T06:43:24.667 回答