我想创建一个简单的应用来跟踪房间里的人。我想要2个人和房间。 像这样的东西
class Person(models.Model):
name = models.CharField()
class Room(models.Model):
number = models.IntegerField()
max_occupancy = models.IntegerField() //set up max person in room
我的问题是:
如何将空间分配给人我可以只使用外键吗? 我有机会检查房间里的人数吗?
答案 0 :(得分:1)
这可能有效:
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)
例如:
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']
如果您希望将某人分配到多个房间,我们可以使用ManyToManyField
并更新占用人数。