我有三个Django模型,即User,Project和Hourly。
此外,我使用ProjectManager()类覆盖Project.objects.create(...。)方法。这意味着我想在创建新项目时生成8760个新的每小时实例。怎么实现这个?目前,每次只创建一个Hourly对象时,调用Projects.object.create()。
Project和Hourly模型以及ProjectManager定义如下:
User = settings.AUTH_USER_MODEL
class ProjectManager(models.Manager):
""""""
def create(self, owner, project_name, TMZ, lat, lon):
project = super().create(owner=owner, project_name="CREATED BY PROJECTMANAGER", TMZ=TMZ, lat=lat, lon=lon)
project.save()
# Next I would like to delete all existing Hourly objects tied to this project
hourly = Hourly.objects.filter(project=project)
hourly.delete()
# Next I would like to generate 8760 new Hourly instances
hourly = []
for i in range(0, 8760):
clock_time=3600*i
hourly[i] = Hourly(project=project, clock_time=clock_time) #, delta=0)
hourly[i].save()
return project
#project = Project(owner=owner, project_name="CREATED BY PROJECTMANAGER", TMZ=TMZ, lat=lat, lon=lon)
class Project(models.Model):
objects = ProjectManager()
owner = models.ForeignKey('auth.User', related_name='projects', on_delete=models.CASCADE)
project_name = models.CharField(max_length=200)
TMZ = models.FloatField(default=0)
lat = models.FloatField(default=0) # Radians
lon = models.FloatField(default=0) # Radians
class Hourly(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE)
clock_time = models.FloatField(default=0) # One year = 31557600 seconds primary_key=True,
@property
def local_civil_time(self):
diff = -3600*self.project.TMZ + 43200*self.project.lon/math.pi
local_time = self.clock_time + diff
return round(local_time)
答案 0 :(得分:4)
以下代码非常高效,可以一次创建多个实例进行优化
hourly = []
for i in range(0, 8760):
clock_time=3600*i
hourly.append(Hourly(project=project, clock_time=clock_time))
Hourly.objects.bulk_create(hourly)
return project
答案 1 :(得分:1)
如果在创建Project对象后没有将小时列表用于其他内容,则无需将其附加到列表中。你只需要:
for i in range(0, 8760):
clock_time=3600*i
hourly = Hourly(project=project, clock_time=clock_time)
hourly.save()
但你必须要知道,在数据库中保存8760个对象是数据库的一项密集任务。