简体   繁体   中英

Create multiple Django model instances using for loop

I have three Django models namely User, Project and Hourly.

  1. User model: which represents a standard Django user, which can start a new project.
  2. Project model: Represents a project, containing project specifc constants such as Time Zone, site latitude, site longitude, etc…
  3. Hourly model: Which represents all the hourly values (clock-time, solar time, solar hour angle, etc…) for a certain project. To simplify the problem the Hourly model has only two fields, namely project and clock_time. Eventually I would like to use fields to store these to the database.

In addition I override the Project.objects.create(….) method using the ProjectManager() class. The meaning of this is that I would like to generate 8760 new hourly instances whenever a new project is created. How to implement this? At the moment every time only one Hourly object is created, whener Projects.object.create() is called.

The Project and Hourly models and the ProjectManager are defined as follows:

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)

This below code is very efficient and optimise for create many instances at a time

    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

If you are not using the hourly list for something else after the creation of the Project object, then you do not need to append it to the list. You only need to:

for i in range(0, 8760):
    clock_time=3600*i
    hourly = Hourly(project=project, clock_time=clock_time)
    hourly.save()

but you have to be aware that save 8760 objects in the database is an intensive task for the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM