-1
以下の3つのテーブルをループし、Masterテーブルにレコードを作成する以下のクエリがあります。クエリは機能しますが、可能であれば、Django QuerySet APIを利用して効率を上げ、クエリを改善する方法を知りたかったのです。クエリ最適化を呼び出すためのDjango QuerySet API
Djangoのクエリ:
s = Schedule.objects.get(pk = s_pk)
order = s.ordering_set.all()
days = s.dayscheduler_set.all()
for z in days:
for x in order:
s_val = x.room.spacetype.pk
s = Space.objects.get(pk = s_val)
q = Group.objects.filter(space = s, is_default = True)
for y in q:
daySch = DayScheduler.objects.get(pk=z.pk)
room = Room.objects.get(pk=x.room.pk)
group = Group.objects.get(pk = y.pk)
M = Master.objects.create(room = room, dayScheduler = daySch, group = group)
M.save()
Djangoのモデル:あなたがiterator()
メソッドを使用することができ、すべての
@python_2_unicode_compatible # only if you need to support Python 2
class Schedule(models.Model):
building = models.ForeignKey(Building, on_delete = models.CASCADE)
schedule_name = models.CharField(max_length=200)
def __str__(self):
return self.schedule_name
@python_2_unicode_compatible # only if you need to support Python 2
class Ordering(models.Model):
schedule = models.ForeignKey(Schedule, on_delete = models.CASCADE)
order_number = models.IntegerField()
room = models.ForeignKey(Room, on_delete = models.CASCADE)
def __str__(self):
return str(self.order_number)
@python_2_unicode_compatible # only if you need to support Python 2
class Room(models.Model):
building = models.ForeignKey(Building, on_delete = models.CASCADE)
room_name = models.CharField(max_length=200)
rmfloor_name = models.ForeignKey(Floor, on_delete = models.CASCADE)
sqfootage = models.IntegerField()
spacetype = models.ForeignKey(Space, on_delete = models.CASCADE)
barcode_name = models.CharField(max_length=100)
def __str__(self):
return self.room_name
@python_2_unicode_compatible # only if you need to support Python 2
class DayScheduler(models.Model):
is_applicable = models.BooleanField(default = True)
schedule = models.ForeignKey(Schedule, on_delete = models.CASCADE)
dayOfWeek = models.ForeignKey(DayofWeek, on_delete = models.CASCADE)
user = models.ForeignKey(User, blank=True, null=True)
def __str__(self):
return str(self.pk)
@python_2_unicode_compatible # only if you need to support Python 2
class Group(models.Model):
group_name = models.CharField(max_length=200)
space = models.ForeignKey(Space, on_delete = models.CASCADE)
building = models.ForeignKey(Building, on_delete = models.CASCADE)
is_default = models.NullBooleanField()
task = models.ManyToManyField(Task)
def __str__(self):
return str(self.group_name)
@python_2_unicode_compatible # only if you need to support Python 2
class Master(models.Model):
room = models.ForeignKey(Room, on_delete = models.CASCADE)
dayScheduler = models.ForeignKey(DayScheduler, on_delete = models.CASCADE)
group = models.ForeignKey(Group, on_delete = models.CASCADE, blank=True, null=True)
def __str__(self):
return str(self.pk)