Django: ‘long’ object has no attribute ‘encode’

Not the movie 🙂

I’m following the Django tutorial and it’s surprisingly fun! I ran into an issue that I’m going to document here for any hapless souls that come after me. To seasoned Python devs, it’s blindingly obvious but I’m a newbie. 

In the tutorial, we’re only supposed to create 2 models (Poll and Choice) but I decided to add an extra model to my file:

    class Transaction(models.Model):
        groceryitem = models.IntegerField()
        store_name = models.CharField(max_length=255)
        transaction_id = models.IntegerField(default=1)
        purchase_date = models.DateTimeField(‘date purchased’)
        def __unicode__(self):
            return self.transaction_id

After adding the Transaction model to the admin page to be edited, I was unable to view and got this error message:

Exception Type: AttributeError
Exception Value: ‘long’ object has no attribute ‘encode’

When i switched to the interactive shell to check on my Transaction objects, I got this very helpful error message.

>>> Transaction.objects.all():


TypeError: coercing to Unicode: need string or buffer, long found

When I defined __unicode__ for the Transaction model, I should output a string object instead of the number. Defining __unicode__ is analogous to defining the toString() method in Java (correct me if I’m wrong). To solve y The last line of my Transaction model group of statements should have been:

return str(self.transaction_id)