Reverse of OneToOneField relationships are being cached improperly, returning wrong model class
|Reported by:||gav||Owned by:||nobody|
|Severity:||Keywords:||121, related_name, cache|
|Cc:||m.gajda@…, anossov@…, michal@…||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
When following a reverse relationship, the cache where the objects pulled from the database are stored is not using the proper variable name for storing the reverse result. Two models both related to the original model will cause the relation to be overwritten on the second access, assuming that both models are related to the original model by the same name (and therefore are forced by the forward relationship to have a related_name attribute to distinguish them).
The solution, provided by Travis Terry (patch attached), is to cache by using the related_name instead of the field name.
Here's an example:
class Test4(models.Model): b = models.CharField(max_length=10) class Test5(models.Model): c = models.CharField(max_length=10) f2 = models.OneToOneField(Test4, related_name='first_link') class Test6(models.Model): d = models.CharField(max_length=10) f2 = models.OneToOneField(Test4, related_name='second_link') # This shows how to trigger the error. t4 = Test4.objects.create(b='Thing1') t5 = Test5.objects.create(c='obj1', f2=t4) t6 = Test6.objects.create(d='obj2', f2=t4) a = Test4.objects.get(pk=t4.id)
Here's what you get:
>>> print a.first_link Test5 object >>> print a.first_link.c obj1 >>> print a.second_link Test6 object >>> print a.second_link.d Traceback (most recent call last): ... AttributeError: 'Test5' object has no attribute 'd'
Here's what you should get:
>>> print a.first_link Test5 object >>> print a.first_link.c obj1 >>> print a.second_link Test6 object >>> print a.second_link.d obj2
Change History (8)
Changed 7 years ago by gav
comment:1 Changed 7 years ago by gav
- Component changed from Uncategorized to Core framework
- Has patch set
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset