0

How do i restrict the user to save objects in 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)

i want to limit the foo only for 10 entries per user

i am using mysql as a backend

the_thor
  • 53
  • 1
  • 6
  • if you use postgre as backend db, you could use stuff like [ArrayFields](https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/). And for these arrays, cou could control length, content etc. – nichoio Apr 28 '17 at 06:20
  • i am using mysql as backend – the_thor Apr 28 '17 at 06:21
  • Yeah, already noticed, my bad. Maybe you could switch the underlying db depending on your requirements etc. You have always the option to execute code [before a model field becomes saved](https://docs.djangoproject.com/en/1.11/ref/signals/#django.db.models.signals.pre_save), so this could be a useful hack for you too. – nichoio Apr 28 '17 at 06:25
  • is there any way to validate in forms.py – the_thor Apr 28 '17 at 06:27
  • If you want to achieve it in form.py, I guess the most intuitive way is to check the number of foo in DB before user insert/update foo. If num of records>10, response error msg to user. – CK Chen Apr 28 '17 at 06:37
  • can u explain it in code @CK Chen – the_thor Apr 28 '17 at 06:38

1 Answers1

4

You can do

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

You can do the same thing if you are using forms by updating Form.clean method

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.")
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49