Foreign Key Relations in Django Bulk_Create Query?

Foreign Key Relations in Django Bulk_Create Query?

Is it possible to use bulk_create method on columns with foreign key relations??

class Reports(models.Model):
    groupname=models.CharField(max_length=250, null=True, blank=True);
    datecreated = models.DateTimeField(null=True, blank=True);


class Reportsquery(models.Model):
    group = models.ForeignKey(Reports,null=True, blank=True);
    queryset=models.CharField(max_length=1000, null=True, blank=True);

list=[Reportsquery({"group__id":6,"queryset":"abc"}),....,...]

Reportsquery.objects.bulk_create(list)

similar query works on get_or_create() method but returns an error when used with bulk_create() eg:

Reportsquery.objects.get_or_create(group__id=6,quseryset="abc")

The above example inserts group__id=6 into Reportsquery table

5

1 Answer

If what you're trying to do is create instances of Reports alongside the Reportsquery, then no bulk_create() won't do this. However, if the instances of Reports already exist in the database then you could manually add their pk's to the list you pass to bulk_create(). Then the Reportquery instances will be created with the correct relations to Reports.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.