Fixed #32332 -- Fixed loss of parent with non-numeric pk when saving child after parent.
PR #13964 ↗ · django/django · · merged Feb 4, 2021 · +22−4 · base f39634ff2298
Agent prompt
what a new run launched now would send
Saving parent object after setting on child leads to data loss for parents with non-numeric primary key.
Description
(last modified by Charlie DeTar)
Given a model with a foreign key relation to another model that has a non-auto CharField as its primary key:
class Product(models.Model):
sku = models.CharField(primary_key=True, max_length=50)
class Order(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
If the relation is initialized on the parent with an empty instance that does not yet specify its primary key, and the primary key is subsequently defined, the parent does not "see" the primary key's change:
with transaction.atomic():
order = Order()
order.product = Product()
order.product.sku = "foo"
order.product.save()
order.save()
assert Order.objects.filter(product_id="").exists() # Succeeds, but shouldn't
assert Order.objects.filter(product=order.product).exists() # Fails
Instead of product_id being populated with product.sku, it is set to emptystring. The foreign key constraint which would enforce the existence of a product with sku="" is deferred until the transaction commits. The transaction does correctly fail on commit with a ForeignKeyViolation due to the non-existence of a product with emptystring as its primary key.
On the other hand, if the related unsaved instance is initialized with its primary key before assignment to the parent, it is persisted correctly:
with transaction.atomic():
order = Order()
order.product = Product(sku="foo")
order.product.save()
order.save()
assert Order.objects.filter(product=order.product).exists() # succeeds
Committing the transaction also succeeds.
This may have something to do with how the Order.product_id field is handled at assignment, together with something about handling fetching of auto vs non-auto primary keys from the related instance.
Work only inside this repository checkout. Make the code change the task
describes, keeping the diff focused — no drive-by refactors.
When you are done, leave your changes committed or in the working tree;
they are collected automatically.
Stay on this snapshot checkout (`task/ycb_django_pr13964`). Never checkout, pull, or rebase onto `main`. That branch is a README-only orphan.
Stay on this HEAD. Do not fetch another default branch. Push only on the Cursor-created `crazy-cursor/…` side branch from this HEAD.
Some past runs of this task were launched with a different prompt (the prompt template changed since, or those runs predate this benchmark's stored prompt). Each run persists the exact prompt it sent at launch — that per-launch record is the audit trail; this page shows only the current one.
Reference diff
The task PR's merged diff — the judge's comparison target.