Django

Code

Ticket #7173 (new)

Opened 1 week ago

Last modified 1 week ago

Reverse of OneToOneField relationships are being cached improperly, returning wrong model class

Reported by: gav Assigned to: nobody
Component: Core framework Version: SVN
Keywords: 121, related_name, cache Cc:
Triage Stage: Unreviewed Has patch: 1
Needs documentation: 0 Needs tests: 0
Patch needs improvement: 0

Description

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

Attachments

related_cache_r7513.patch (0.6 kB) - added by gav on 05/05/08 12:20:29.
Patch from Travis Terry using related_name for the cache field name.

Change History

05/05/08 12:20:29 changed by gav

  • attachment related_cache_r7513.patch added.

Patch from Travis Terry using related_name for the cache field name.

05/05/08 12:21:45 changed by gav

  • needs_better_patch changed.
  • has_patch set to 1.
  • component changed from Uncategorized to Core framework.
  • needs_tests changed.
  • needs_docs changed.

05/05/08 12:22:52 changed by gav

  • keywords set to 121, related_name, cache.

Add/Change #7173 (Reverse of OneToOneField relationships are being cached improperly, returning wrong model class)




Change Properties
Action