Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 572
jithin Avatar asked Jun 02 '14 12:06

jithin


1 Answers

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.

like image 85
Matt Deacalion Avatar answered Sep 27 '22 20:09

Matt Deacalion