Search code examples
djangotypeerrormanytomanyfield

Django TypeError unsupported operand type(s) for +: 'dict' and 'int'


I created a through model so I can add an order field to the m2m field but I am having problems auto incrementing the order field via def number() below. When I add an object, I get TypeError unsupported operand type(s) for +: 'dict' and 'int' and i'm not sure why. Any ideas?

models.py:

class Playlist(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    name = models.CharField(max_length=50)
    tracks = models.ManyToManyField(Track, through='PlaylistTrack')

    def __str__(self):
        return self.name

class PlaylistTrack(models.Model):

    def number():
        last_order = PlaylistTrack.objects.all().aggregate(Max('order'))
        if last_order == None:
            return 1
        else:
            return last_order + 1

    track = models.ForeignKey(Track)
    playlist = models.ForeignKey(Playlist)
    order = models.PositiveIntegerField(default=number)

    class Meta:
        ordering = ['order']

Solution

  • As mentioned in the docs, aggregate() returns a dict object. Hence, the variable last_order is actually a dict and you are trying to add a number to a dict.

    You should get the value from the dict and then add.

    return last_order['order__max'] + 1