Overriding __unicode__

10 views
Skip to first unread message

Mattias Brändström

unread,
Feb 24, 2010, 3:13:04 AM2/24/10
to django-polymorphic
Hello!

Another thing I have noticed that might also be a problem in
django_polymorphic is that overriding __unicode__ does not behave as I
expected. A small example:

class Foo(models.Model):
foo = models.CharField(max_length=100)

def __unicode__(self):
return 'Foo %s' % self.foo

class Bar(PolymorphicModel):
bar = models.CharField(max_length=100)

def __unicode__(self):
return 'Bar %s' % self.bar

In the interactive shell:

>>> from polymorphic_test.polytest.models import *
>>> foo = Foo.objects.create(foo='A')
>>> repr(foo)
'<Foo: Foo A>'
>>> bar = Bar.objects.create(bar='X')
>>> repr(bar)
'<Bar: id 4, bar (CharField)>'

What is going on here? Why does repr(foo) and repr(bar) return
different things. I would have expected repr(bar) to return whatever
Bar.__unicode__() returns.

Regards,
Mattias

Bert Constantin

unread,
Feb 24, 2010, 10:17:06 AM2/24/10
to django-polymorphic
> Another thing I have noticed that might also be a problem in
> django_polymorphic is that overriding __unicode__ does not behave as I
> expected.

This is a result of trying to create a nicely formatted documentation
for django_polymorphic which also is technically exact. The unexpected
behaviour you demonstrated however leads me to conclude that this
should be done differently.

I will probably remove this non-standard behaviour in the next update.

You can do just this right now with the following modifications to the
django_polymorphic source code:

polymorphic/polymorphic_model.py:
- class PolymorphicModel(ShowFieldTypes, models.Model):
+ class PolymorphicModel(models.Model):

polymorphic/query.py:
- def __repr__(self):
- result = [ repr(o) for o in self.all() ]
- return '[ ' + ',\n '.join(result) + ' ]'

This makes polymorphic models behave just like Django models regarding
repr and __unicode__.

Thanks for your report!

Kind Regards,
Bert

Reply all
Reply to author
Forward
0 new messages