使用for循环创建多个Django模型实例

时间:2018-02-13 13:39:47

标签: python django

我有三个Django模型,即User,Project和Hourly。

  1. 用户模型:代表可以启动的标准Django用户 一个新项目。
  2. 项目模型:代表一个项目,包含项目特定常量,如时区,站点纬度,站点经度等......
  3. 每小时模型:代表某个项目的所有小时值(时钟时间,太阳时,太阳时小时等等)。为了简化问题,每小时模型只有两个字段,即project和clock_time。最后我想使用字段将这些字段存储到数据库中。
  4. 此外,我使用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)
    

2 个答案:

答案 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个对象是数据库的一项密集任务。