Python字符串格式返回Property而不是字符串(unicode)?

时间:2012-03-08 22:56:51

标签: python django

我在Django中遇到错误Caught TypeError while rendering: sequence item 1: expected string or Unicode, Property found。这是我的代码:

def __unicode__( self ) :
    return "{} : {}".format( self.name, self.location )

我甚至尝试过

def __unicode__( self ) :
    return unicode( "{} : {}".format( self.name, self.location ) )

但同样的错误。

据我所知"this is x = {}".format( x )返回一个字符串对吗?为什么Python说它是属性?

完整代码:

class Item( models.Model ) :
    def __unicode__( self ) :
        return "{} : {}".format( self.name, self.location )

    name       = models.CharField( max_length = 135 )
    comment    = models.TextField( blank = True )
    item_type  = models.ForeignKey( ItemType )
    location   = models.ForeignKey( Location )
    t_created  = models.DateTimeField( auto_now_add = True, verbose_name = 'created' )
    t_modified = models.DateTimeField( auto_now = True, verbose_name = 'modified' )

class Location( models.Model ) :
    def __unicode__( self ) :
        locations = filter( None, [ self.room, self.floor, self.building ] )
        locations.append( self.prop )

        return ", ".join( locations ) # This will look in the form of like "room, floor, building, property"

    comment    = models.TextField( blank = True )
    room       = models.CharField( max_length = 135, blank = True )
    floor      = models.CharField( max_length = 135, blank = True )
    building   = models.CharField( max_length = 135, blank = True )
    prop       = models.ForeignKey( Property )
    t_created  = models.DateTimeField( auto_now_add = True, verbose_name = 'created' )
    t_modified = models.DateTimeField( auto_now = True, verbose_name = 'modified' )

class Property( models.Model ) :
    def __unicode__( self ) :
        return self.name

    name = models.CharField( max_length = 135 )

2 个答案:

答案 0 :(得分:1)

Property不是指Python属性,而是指Property类。可能发生的是:

  1. Item.__unicode__被召唤。
  2. 它抓取self.nameself.location
  3. self.name__unicode__方法返回一个unicode字符串。
  4. self.location是外键,因此Location.__unicode__会被调用。
  5. 得到self.roomself.floorself.building,它们都有__unicode__方法返回unicode字符串。
  6. filter发现这些字符串都是空的,因此locations设置为[]
  7. self.propProperty,附加到locations
  8. ", ".join( locations )引发TypeError,因为Property不是字符串。
  9. str.format中的Item.__unicode__电话会捕获该异常,并自行投放,这就是您所看到的。
  10. 解决方案:更改

    locations.append( self.prop )
    

    locations.append( unicode(self.prop) )
    

    道德:str.format在其参数上调用str(),但str.join没有。{/ p>

答案 1 :(得分:0)

你试过吗?:

def __unicode__( self ):
    return "{name}: {location}".format(name=self.name, location=self.location)

def __unicode__( self ):
    return "{0}: {1}".format(self.name, self.location)

def __unicode__( self ):
    return "%s: %s" % (self.name, self.location)

希望有所帮助:)