thegooglecodearchive / django-grappelli

Automatically exported from code.google.com/p/django-grappelli
Other
0 stars 0 forks source link

Related lookup fields fails for models with a custom primary key #384

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I've came across something odd when using generic relationship, fortunately 
there's an easy workaround.

It happens when you have a generic relation pointing a model which has a custom 
primary key.

For example, this will not work as expected:

{{{
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Member(models.Model):
    code  = models.IntegerField(primary_key=True, unique=True, editable=False)
    name = models.CharField(max_length=250, blank=True, null=True)

class MemberProfile(ExtendedModel):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    bio    = models.TextField(blank=True, null=True)
}}}

You will get this error:

`Exception Value: Caught AttributeError while rendering: 'Member' object has no 
attribute 'id'`

To fix this, simply add an id property returning your custom primary key like 
this and everything will work fine:

{{{
class Member(models.Model):
    code  = models.IntegerField(primary_key=True, unique=True, editable=False)
    name = models.CharField(max_length=250, blank=True, null=True)

    @property
    def id(self):
        return self.code
}}}

Original issue reported on code.google.com by hainea...@gmail.com on 5 Jul 2011 at 2:58

GoogleCodeExporter commented 9 years ago
thanks ... I´ve updated the docs (r1455).

Original comment by sehmaschine on 17 Jul 2011 at 3:00