Opened 11 years ago
Closed 11 years ago
#22292 closed Bug (duplicate)
Problems with updating a ForeignKey having a to_field attribute
Reported by: | sly010 | Owned by: | nobody |
---|---|---|---|
Component: | Uncategorized | Version: | 1.6 |
Severity: | Normal | Keywords: | ForeignKey to_field |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
class Owner(models.Model):
uid = models.CharField(max_length = 255, unique = True)
class Article(models.Model):
owner = models.ForeignKey(Owner, to_field = 'uid')
owner = ...
article = ...
1
Article.objects.filter(pk = article.pk).update( owner = owner )
# BROKEN
# injects id into the sql instead of uid
# best case fails with integrity error, worst case it silently continues (depends on the content of the tables)
2
Article.objects.filter(pk = article.pk).update( owner = owner.uid )
# WORKS
3
Article.objects.filter(pk = article.pk).update( owner_id = owner.uid )
# FAILS (unrecognized field name)
4
Article.objects.filter(pk = article.pk).update( owner_id = owner )
# FAILS (unrecognized field name)
5
article.owner = owner
article.save(update_field = owner)
# WORKS
6
article.owner = owner.uid
article.save(update_field = owner)
# FAILS
7
article.owner_id = owner.uid
article.save(update_field = owner)
# WORKS
8
article.owner_id = owner
article.save(update_field = owner)
# FAILS
1 and 5 should definitely be working the same way, maybe some pointer as to which one is the preferred way (especially going forward)?