Limit instantiations of class with particular value to one - django
I have two classes in a django app, project
and plan
The project class has an is_global
boolean field, as does the plan class. The plan also has a foreign key to the project class (projects have multiple plans).
I am trying to accomplish the following: for both projects and plans, there should only ever be one instance of each where is_global = true
. The global plan should belong to the global project.
Is it possible to enforce this logic with django models?
You could overwrite the save function of each model to check for prior 'is_global' items
Project Model
def save(self):
if self.is_global:
other_global = Project.objects.filter(is_global=True).exists()
if other_global:
#handle the error, eg, raise an exception or send a message
return
super.save()
Plan model
def save(self):
if self.is_global:
other_global = Plan.objects.filter(is_global=True).exists()
if other_global:
#handle the error, eg, raise an exception or send a message
return
if not self.project.is_global:
#handle the error, eg, raise an exception or send a message
return
super.save()