Reputation: 352
I just want to store a single or may be just two objects in model but not more. And no one can add more objects in that model.How can I do that is there any option in django to use it?
Basically I just want to specify the range of objects store in models.
Thank You.
Upvotes: 1
Views: 410
Reputation: 205
You can override the save method and set a condition
class Test(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if Test.objects.count() > 1:
raise ValidationError("You can't save more than two items")
super(Test, self).save(*args, **kwargs)
Upvotes: 2
Reputation: 2018
You can do this
Suppose I have people model and I want that only two records should be created then
class People(models.Model):
name = models.CharField(max_length=255)
def save(self,*args,**kwargs):
if People.objects.count() > 1:
return False # or you can raise validation error
else:
super(People,self).save(*args,**kwargs)
Upvotes: 3