Search code examples
pythondjangodjango-modelsdjango-database

What is a right method to apply relations between database?


I want to create simple app to tracking people in rooms. I want have 2 table person and room. Something like this

class Person(models.Model):
name = models.CharField()

class Room(models.Model):
number = models.IntegerField()
max_occupancy = models.IntegerField() //set up max person in room

My questions are:

How I assign room to person can I use just foreign key? Is there any chance I can check number of persons in room?


Solution

  • This might work:

    from django.core.exceptions import ValidationError
    
    class Room(models.Model):
        number = models.IntegerField()
        max_occupancy = models.IntegerField() #set up max person in room
    
    class Person(models.Model):
        name = models.CharField(max_length=16)
        room = models.ForeignKey(Room, related_name='persons')
    
        def save(self, *args, **kwargs):
            if self.room:# not necessary if the field is not nullable
                if self.room.persons.count() >= self.room.max_occupancy :
                    raise ValidationError('Room is already full')
            super().save(*args, **kwargs)
    

    For example:

    r = Room.objects.create(number=1, max_occupancy=1)
    Person.objects.create(name='first', room=r)
    # creates
    Person.objects.create(name='second', room=r)
    # ValidationError: ['Room is already full']
    

    If you want a person to be assigned to multiple rooms, we can use ManyToManyField and also update the checking of occupants count.