How to define a relationship in Django Models such that a space in a model can be allocated to an object without overlapping?

I need to define models in Django such that it should check the server objects can fit into the rack object in question without overlapping each other and that you only use as many space(in Us) as you actually have in the rack. I tried defining the Django model as follows:

from django.db import models
class Location(models.Model):
    name = models.CharField(max_length =200)

    def __str__(self):
        return str(self.name)

class Rack(models.Model):
    id = models.IntegerField(primary_key = True, auto_created = True)
    size = models.IntegerField()
    location = models.ManyToManyField(Location)
    def __str__(self):
        return str(self.id)
class Server(models.Model):
    id = models.IntegerField(primary_key= True, auto_created=True)
    size = models.IntegerField()
    rack_id = models.ForeignKey(Rack, on_delete=models.CASCADE)
    owner = models.CharField(max_length = 200)
    locations = models.OneToOneField(Location, on_delete=models.CASCADE)

    def __str__(self):
        return  str(self.id)

I am unsure how to define the locations such that if I choose a location for a server, it is assigned to a location within the Rack, without overlapping the same location by any other server. At the same time, I need to make sure I only use as many space(in Us) as I actually have in the rack.

Back to Top