4

For example, I have two models:

class Person(models.Model):
    name = models.CharField(max_length=100)

class Job(models.Model):
    title = models.CharField(max_length=100)
    person = models.ForeignKey(Person)

I have a list of job ids--

job_ids = [1, 2, ....] 

that are pks of Job model instances

I know I can do--

for id in job_ids:
    person.jobs.add(job_id)

but this will be many more queries than if I could do--

person.jobs.add(job_ids)

where it would unpack the list and use bulk_create. How do I do this? Thanks.

Dakin Sloss
  • 81
  • 1
  • 5

2 Answers2

3

Have you tried

person.jobs.add(*job_ids)

In my case I used a filter query and had a list of objects (as opposed to IDs). I was getting an error similar to

TypeError: 'MyModel' instance expected, got [<MyModel: MyModel Object>]

...before I included the asterisk.

credit (another SO question)

Mike S
  • 1,537
  • 2
  • 11
  • 15
0

If you didn't create your jobs yet, you can create them by adding bulk=False

jobs_list=[
     Job(title='job_1'),
     Job(title='job_2')
[

person.jobs.add(*jobs_list, bulk=False) # your related_name should be 'jobs', otherwhise use 'job_sets'.