Ticket #12664: generic_relation_pk_fix.1.diff

File generic_relation_pk_fix.1.diff, 3.0 KB (added by jbronn, 15 years ago)
  • django/contrib/contenttypes/generic.py

     
    129129        return self.object_id_field_name
    130130
    131131    def m2m_reverse_name(self):
    132         return self.model._meta.pk.column
     132        return self.rel.to._meta.pk.column
    133133
    134134    def contribute_to_class(self, cls, name):
    135135        super(GenericRelation, self).contribute_to_class(cls, name)
  • tests/regressiontests/generic_relations_regress/tests.py

     
    11from django.test import TestCase
    22from django.contrib.contenttypes.models import ContentType
    3 from models import Link, Place, Restaurant
     3from models import Link, Place, Restaurant, Person, Address
    44
    55class GenericRelationTests(TestCase):
    66   
     
    1616        l2 = Link.objects.create(content_object=r)
    1717        self.assertEqual(list(p.links.all()), [l1])
    1818        self.assertEqual(list(r.links.all()), [l2])
    19        
    20  No newline at end of file
     19       
     20    def test_reverse_relation_pk(self):
     21        """
     22        Test that the correct column name for the primary key is used on the
     23        originating model during a query.
     24        """
     25        p = Person.objects.create(account=23, name='Chef')
     26        a = Address.objects.create(street='123 Anywhere Place',
     27                                   city='Conifer', state='CO',
     28                                   zipcode='80433', content_object=p)
     29       
     30        qs = Person.objects.filter(addresses__zipcode='80433')
     31        self.assertEqual(1, qs.count())
     32        self.assertEqual('Chef', qs[0].name)
  • tests/regressiontests/generic_relations_regress/models.py

     
    1919   
    2020class Restaurant(Place):
    2121    def __unicode__(self):
    22         return "Restaurant: %s" % self.name
    23  No newline at end of file
     22        return "Restaurant: %s" % self.name
     23
     24class Address(models.Model):
     25    street = models.CharField(max_length=80)
     26    city = models.CharField(max_length=50)
     27    state = models.CharField(max_length=2)
     28    zipcode = models.CharField(max_length=5)
     29    content_type = models.ForeignKey(ContentType)
     30    object_id = models.PositiveIntegerField()
     31    content_object = generic.GenericForeignKey()
     32
     33    def __unicode__(self):
     34        return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode)
     35
     36class Person(models.Model):
     37    account = models.IntegerField(primary_key=True)
     38    name = models.CharField(max_length=128)
     39    addresses = generic.GenericRelation(Address)
     40
     41    def __unicode__(self):
     42        return self.name
Back to Top