سؤال

I have the following code at the unicode representation of a django models.Model:

def __unicode__(self):
    if self.right:
        return u"{left} ({left_score}) | {right} ({right_score})".format({
            'left': self.left, 
            'left_score': self.left_score, 
            'right': self.right, 
            'right_score': self.right_score,
        })
    else:
        return "%s" % self.left

I get

Exception Type: KeyError
Exception Value: u'left'

I also tried using unicode keys in the dictionary. self.left is not None.
I have read lots of forums still can't figure out what I am doing wrong. :(

How can I fix this?

هل كانت مفيدة؟

المحلول

The format method requires you to pass your arguments as kwargs, not as a dictionary.

def __unicode__(self):
    if self.right:
        return u"{left} ({left_score}) | {right} ({right_score})".format(
            left=self.left, 
            left_score=self.left_score, 
            right=self.right, 
            right_score=self.right_score,
        )
    else:
        return "%s" % self.left

نصائح أخرى

You can also unpack stored dictionary in place:

left, right = 'L', 'R'
left_score, right_score = "LS", "RS"

print u"{left} ({left_score}) | {right} ({right_score})".format(**{
            'left': left, 
            'left_score': left_score, 
            'right': right, 
            'right_score': right_score,
        })

Out: L (LS) | R (RS)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top