Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#27026 closed Bug (fixed)

Objects not fully configured after bulk_create.

Reported by: Sjoerd Job Postmus Owned by: nobody
Component: Database layer (models, ORM) Version: 1.10
Severity: Release blocker Keywords: bulk_create, postgresql, ManyToManyField
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Objects not fully configured after bulk_create.

When running bulk_create on multiple objects, the primary key now gets set (if using postgresql), but the _state field does not get updated.

This makes some features of the ORM work with the newly "id"-ed objects, but others not.

In particular, the following case fails:

#models.py
class Country(models.Model):
    name = models.CharField(max_length=255)
    iso_two_letter = models.CharField(max_length=2)


class Union(models.Model):
    name = models.CharField(max_length=255)
    countries = models.ManyToManyField(Country)


#tests.py
    @skipUnlessDBFeature('can_return_ids_from_bulk_insert')
    def test_set_pk_and_allow_creating_related(self):
        union_eu = Union.objects.create(name='EU')
        country_nl = Country(name='Netherlands', iso_two_letter='NL')
        with self.assertNumQueries(1):
            Country.objects.bulk_create([country_nl])
        union_eu.countries.add(country_nl)

Change History (5)

comment:1 Changed 3 years ago by Sjoerd Job Postmus

A pull request is available at https://github.com/django/django/pull/7033.

comment:2 Changed 3 years ago by Simon Charette

Severity: NormalRelease blocker
Triage Stage: UnreviewedAccepted

Accepting as a 1.10 release blocker since it's a bug in a newly released feature.

comment:3 Changed 3 years ago by Sjoerd Job Postmus

This is the exception that occurred.

ValueError: Cannot add "<Country: Country object>": instance is on database "default", value is on database "None"

comment:4 Changed 3 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: newclosed

In 3246d2b4:

Fixed #27026 -- Fixed state initialization of bulk_create() objects if can_return_ids_from_bulk_insert.

comment:5 Changed 3 years ago by Tim Graham <timograham@…>

In 2f18cbc3:

[1.10.x] Fixed #27026 -- Fixed state initialization of bulk_create() objects if can_return_ids_from_bulk_insert.

Backport of 3246d2b4bb981a8d782a349a99e9b89206028cee from master

Note: See TracTickets for help on using tickets.
Back to Top