On Mon, 2007-10-15 at 00:10 -0500, Jeremy Dunck wrote:
> On 10/14/07, Kenneth Gonsalves <[EMAIL PROTECTED]> wrote:
> ...
> > class Sponsorship(models.Model):
> > """ links child to sponsor, startdate enddate and comments"""
> > sponsor = models.ForeignKey(Sponsor,verbose_name=_("Sponsor"))
> > child = models.ForeignKey(Child,verbose_name=_("Child"))
> > class Admin:
> > pass
> > def __unicode__(self):
> > return "%s: %s" %(self.sponsor,self.child)
>
> Maybe I'm silly, but shouldn't this:
> def __unicode__(self):
> return "%s: %s" %(self.sponsor,self.child)
>
> be more like this:
> def __unicode__(self):
> return u"%s: %s" %(self.sponsor,self.child)
Technically, yes, but in practice it probably doesn't matter (although
it might be disguising some other problem). There are two things going
on here that usually save the day in this case.
Firstly, the result of '%s' % foo will be a unicode object if 'foo' is a
unicode object (but not necessarily if it is coercable to unicode -- if
it is also coercable to str, the result will be a str object). Your
preferred method -- u'%s' % foo -- forces things to unicode a bit more
directly and is a little safer in general, so a good habit to get into.
Secondly, no matter what you try to return from __unicode__, Python will
always force the result (at the C library level) into a unicode object.
So return 'apple' from __unicode__ will actuall result in u'apple'. This
usually isn't a problem and is actually the right thing. If the forcing
to a unicode object can't happen (because, say, you're trying to return
a dictionary), an TypeError is raised.
It's worth noting that this coercion does become a real problem when you
try to do the same from __str__ (Python will similarly force the result
to a str at the C level) and return a unicode object from __str__.
That's a common source of bugs. However, in the __unicode__ case, it
will result in corrupted displays, rather than encoding problems, as a
rule.
So, in the rare case where, say, self.sponsor is a UTF-8 string,
Kenneth's version might lead to trouble down the track -- but I would
have thought that trouble would be mis-displayed strings, rather than a
crash.
Still, it would be worth checking that self.sponsor and self.child
really are Unicode strings (and not bytestrings) in the case where a
crash occurs, Kenneth. Or at least working out what they *are* when the
crash occurs.
Regards,
Malcolm
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---