Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

555
Views
Django bulk create with self reference foreign key

I have a question about Django objects creation using bulk_create()

Here is a part of my model :

class Group(models.Model):
    uid = models.IntegerField(unique=True)
    persons = models.ManyToManyField(User, blank=True)
    label = models.CharField(max_length=128)
    parent_group = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)

And then I want to create like this :

df_records = df.to_dict('records')
model_instances = [Group(
    uid = record["uid"],
    label = record["label"],
    group_parent = Group(uid=record["parent_uid"]),
    ) for record in df_records]
Group.objects.bulk_create(model_instances)

Is it possible to self-reference parents in a bulk create (of course the parent is in the same bulk)? Or do I have to set parent to null and iterate throughout all objects to find the parent Django object id?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Thanks to @Willem,

I post here my working code :

class Group(models.Model):
    uid = models.IntegerField(unique=True, primary_key=True)
    persons = models.ManyToManyField(User, blank=True)
    label = models.CharField(max_length=128)
    parent_group = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)

and the bulk_create

df_records = df.to_dict('records')
model_instances = [Group(
    uid = record["uid"],
    label = record["label"],
    group_parent_id = record["parent_uid"],
    ) for record in df_records]
Group.objects.bulk_create(model_instances)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!