Populate Django Model with for-loop
Question:
I have a model Task
which I want to populate with a for loop.
In a list I have the tasks that should be passed into the model.
My model has actually more than three tasks (Below I have shown only three). The list will also have varying number of entries. The list can also have only one task.
tasks = ['first task', 'second task', 'third task']
class Task(models.Model):
ad = models.OneToOneField(Ad, on_delete=models.CASCADE, primary_key=True, blank=True, null=False)
task1 = models.CharField(max_length=256, blank=True, null=True)
task2 = models.CharField(max_length=256, blank=True, null=True)
task3 = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return f'Tasks for {self.ad}'
My approach looks like this:
task_obj = Task.objects.create(
ad = ad
)
for idx, t in enumerate(tasks):
task_obj.f'task{idx+1}' = t
Basically this part f'task{idx+1}'
should not be a string, but the actual variable of the model.
Is this even possible? Or does an other way exist I am not aware of?
Answers:
You can use the setattr
built-in function to set dynamic attributes:
for idx, t in enumerate(tasks):
setattr(task_obj, f'task{idx+1}', t)
I have a model Task
which I want to populate with a for loop.
In a list I have the tasks that should be passed into the model.
My model has actually more than three tasks (Below I have shown only three). The list will also have varying number of entries. The list can also have only one task.
tasks = ['first task', 'second task', 'third task']
class Task(models.Model):
ad = models.OneToOneField(Ad, on_delete=models.CASCADE, primary_key=True, blank=True, null=False)
task1 = models.CharField(max_length=256, blank=True, null=True)
task2 = models.CharField(max_length=256, blank=True, null=True)
task3 = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return f'Tasks for {self.ad}'
My approach looks like this:
task_obj = Task.objects.create(
ad = ad
)
for idx, t in enumerate(tasks):
task_obj.f'task{idx+1}' = t
Basically this part f'task{idx+1}'
should not be a string, but the actual variable of the model.
Is this even possible? Or does an other way exist I am not aware of?
You can use the setattr
built-in function to set dynamic attributes:
for idx, t in enumerate(tasks):
setattr(task_obj, f'task{idx+1}', t)