我正在尝试使用Django的旅馆管理系统。该系统可以允许用户注册租户并为他们分配特定楼层的房间。
我想在django-admin中创建一个5层的旅馆,每层有50个房间。如何将地板和房间添加到models.py?
我对Django的了解不是很丰富,您的回复确实可以帮助我学习很多东西。
答案 0 :(得分:0)
您可以从类似
开始class Hostel(models.Model):
pass # maybe add `name`, etc?
class Floor(models.Model):
hostel = models.ForeignKey(Hostel, on_delete=models.PROTECT)
floor_number = models.IntegerField()
class Meta:
unique_together = (("hostel", "floor_number"),)
class Room(models.Model):
floor = models.ForeignKey(Floor, on_delete=models.PROTECT)
room_number = models.IntegerField()
# you might add `capacity`, etc. here
class Meta:
unique_together = (
("floor", "room_number"),
("floor__hostel", "room_number"),
)
unique_together
子句确保
然后,您可能希望使用管理命令或其他脚本来植入这些种子:
hostel = Hostel.objects.create()
for floor_number in range(1, 6): # Floors from 1 to 5
floor = Floor.objects.create(
hostel=hostel, floor_number=floor_number
)
for room_number_in_floor in range(1, 51): # Rooms from 1 to 50 per floor
# Translate floor 1, room 10 into 110, etc.:
room_number = floor_number * 100 + room_number
room = Room.objects.create(
floor=floor, room_number=room_number
)
然后您就可以了!祝好运。 :)