[Answer]-Add instance methods to User object that uses related models

1👍

Use backward relationships. For example:

def total_items(self):
    self.item_set.all().count()

If you want to write the logic in the Items model instead of User then you have to import this model inside the User‘s method:

def total_items(self):
    from items.models import Items
    return Items.objects.count_for_user(self)

The Items model/manager will be something like this:

class ItemsManager(models.Manager):

    def count_for_user(self, user):
        return self.filter(user=user).count()

class Items(models.Model):
    ...
    objects = ItemsManager()

Leave a comment