将实例方法添加到使用相关模型的用户对象



我正在使用自定义用户模型,类似于文档中的示例,我想将一些实例方法附加到此用户模型。

假设我还有一些其他模型,例如Items,Polls,ForumPost,BuySell,UpDownVote等,它们都具有用户模型的外键。

然后,我想要实现的是一些自定义方法,我可以在用户对象上调用这些方法,例如,在摘要页面上。像这样的事情:

user.total_items()     - Counts the total items a user has
user.last_forum_post() - Last post the user has made
user.updown_vote_sum() - The sum of all Up and Down votes the user has retrieved

我如何实现这一点?我如何以最佳方式实现它?

我想我可以向我的自定义用户模型添加很多方法,然后执行类似 Items.objects.filter(user=self).count() 的操作。但是,这是正确的做法吗?

使用向后关系。 例如:

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

如果你想在Items模型中编写逻辑而不是User那么你必须在User的方法中导入这个模型:

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

Items模型/管理器将是这样的:

class ItemsManager(models.Manager):
    def count_for_user(self, user):
        return self.filter(user=user).count()
class Items(models.Model):
    ...
    objects = ItemsManager()

最新更新