Home > Blockchain >  django bulk_create with Null value
django bulk_create with Null value

Time:03-22

models.py

class control(models.Model):
    amount = models.IntegerField()
    driver = models.ForeignKey(driver, on_delete=models.CASCADE, null=True, blank=True)

views.py

controlValues = [
    (1,1,1),
    (2,8,None)
]
control.objects.bulk_create([
    control(
        id = i[0],
        amount = i[1],
        driver = driver(id = i[2])
    ) for i in controlValues], ignore_conflicts=True
)

I got error: bulk_create() prohibited to prevent data loss due to unsaved related object 'driver'. How can I set Null for driver? I'm using mysql.

CodePudding user response:

If the value is None, you should not construct a driver model with that object, but thus work with:

control.objects.bulk_create([
    control(
        id=id,
        amount=amount,
        driver=driver(id=dr_id) if dr_id is not None else None
    ) for id, amount, dr_id in controlValues],
    ignore_conflicts=True
)

or a lot simpler:

control.objects.bulk_create([
    control(
        id=id,
        amount=amount,
        driver_id=dr_id
    ) for id, amount, dr_id in controlValues],
    ignore_conflicts=True
)

Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from driver to Driver.

  • Related