Jason Howard
Jason Howard

Reputation: 1586

Preventing more than X instances of a model from being created

I want to create some sort of validation that prevents more than 3 instance of a certain model from being created that meet a certain set of criteria.

1) These model instances are ONLY created in /admin (i.e there is no view that creates these models, thus, I can't do the validation in a view

2) My understanding is that def clean() within forms.py only applies to font facing forms that you'd see on a webpage. As these model instances are only created in the backend, again, I don't think that I can create a form and use def clean() to perform this validation

3) I considered creating a validator in my models.py to do this validation, but I'm not sure how to get the instance of the model within a validator. My understanding is that validators can only be used to validate data at a field level.

This leaves me with some confusion. I'm not sure where I can perform my validation to ensure that only 3 instances of a model with X criteria is ever created.

Thanks for your help!

Upvotes: 0

Views: 38

Answers (1)

Apeal Tiwari
Apeal Tiwari

Reputation: 154

This code checks for add permisson and According to your requirement you can use it to change permisson to false. In your case model.Examplemodel.objects.count()==3

from django.contrib import admin
from myapp import models

@admin.register(models.ExampleModel)
class ExampleModelAdmin(admin.ModelAdmin):

# some code...

def has_add_permission(self, request):
    # check if generally has add permission
    retVal = super().has_add_permission(request)
    # set add permission to False, if object already have 3 instances
    if retVal and models.ExampleModel.objects.count()==3:
        retVal = False
    return retVal

Upvotes: 1

Related Questions