In costcenter.models, I have these these classes:
class CostCenter(models.Model):
costcenter = models.CharField("Cost Center", max_length=6, unique=True)
class ForecastAdjustment(models.Model):
costcenter = models.ForeignKey(
CostCenter, on_delete=models.CASCADE, null=True, verbose_name="Cost Center"
)
In lineitems.models, I have this class which depends on costcenter import:
from costcenter.models import CostCenter
class LineItem(models.Model):
costcenter = models.ForeignKey(CostCenter, on_delete=models.RESTRICT)
I want to extend the save method of ForecastAdjustment so that an exception is raised if no line items exist for the given costcenter. My approach would be to add a method to my CostCenterManager:
class CostCenterManager(models.Manager):
from lineitems.models import LineItem #good enough to avoid circular reference
def has_line_items(self,costcenter:'CostCenter'): #Requires LineItem import. Circular reference.
return LineItem.objects.exists(costcenter=costcenter)
Then above method would be used by the ForecastAdjustment save method:
class ForecastAdjustment:
[...]
def save(self, *args, **kwargs):
if not CostCenterManager.has_line_items(self.costcenter):
raise exceptions.LineItemsDoNotExistError(
f"{self.costcenter} has no line items. Forecast adjustment rejected."
)
Is it reasonable to import LineItem inside my has_line_item method or is there a better approach?