django-activity-stream中follow()无反应,因target未注册为actor,需用registry.register()显式注册;actor_stream()为空因只查用户作为actor的动作,非关注对象动作。

django-activity-stream 装了但 follow() 没反应?检查 User 和 Actor 的关系
默认情况下,django-activity-stream 要求被关注对象(target)必须是 Django 的 User 实例,或者实现了 get_absolute_url() 且能被序列化的模型。如果你对自定义模型(比如 Project 或 Repository)调用 follow(user, target) 却没生成 activity,大概率是 target 没注册为 actor。
解决方法很简单:
- 确保目标模型在
models.py中继承了ActivityStreamModel(旧版)或已通过register()注册(新版 3.x+) - 新版推荐显式注册:
from actstream import registry<br>registry.register(User, Project, Repository)
- 确认
target实例不为None,且已保存到数据库(follow()不接受 unsaved 对象)
为什么 actor_stream(user) 返回空?查 action_object 和权限过滤
actor_stream() 只返回该用户作为 执行者(actor) 的动作,不是“他关注的人干了啥”。GitHub 风格的首页 feed 实际要的是 user_feed = user.actor_actions.all() | user.target_actions.all() | user.action_object_actions.all(),但更常用的是 user.following.stream()。
常见漏点:
-
following.stream()默认只包含 public actions(public=True),如果你创建 action 时没传public=True(例如Action.objects.create(actor=user, verb='pushed', action_object=commit, public=True)),它就不会出现在流里 - 未登录用户调用
stream会返回空——follow()是基于用户 session 或 auth 的,匿名用户无法建立 follow 关系 - 数据库里
action表的timestamp字段若为未来时间,stream()可能因分页逻辑跳过它(尤其搭配timeframe参数时)
如何让 commit、issue、pull request 这类细粒度操作进 Activity 流?别硬塞 Action.objects.create()
手动创建 Action 对象容易出错:字段缺失、时间错乱、反向关系断裂。应该用 action.send() 触发信号,由 signal handler 自动处理。
Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译
例如在 models.py 中监听 post_save:
from django.db.models.signals import post_save<br>from actstream import action<br><br>def on_commit_saved(sender, instance, created, **kwargs):<br> if created:<br> action.send(instance.author, verb='committed', action_object=instance, target=instance.repository)
注意三点:
-
verb必须是字符串,不能是变量名(比如别写verb=VERB_COMMIT却忘了定义) -
target和action_object类型不同:target是“动作发生的上下文”(如仓库),action_object是“被操作的主体”(如某次 commit) - 如果
instance.author是None(比如系统自动提交),action.send()会静默失败,建议加if instance.author:守卫
部署后 activity 流变慢甚至超时?先关掉 GenericForeignKey 的 select_related
actstream 的 Action 模型大量使用 GenericForeignKey,默认查询时不会预加载关联对象,导致 N+1 查询。首页 feed 拉 20 条 activity,可能触发上百次 DB 查询。
优化手段有限但有效:
- 用
action_object_content_type+action_object_object_id手动 prefetch:对常见类型(如User,Repository)做批量查询再映射 - 避免在模板中直接访问
action.actor.get_full_name这类属性;改用select_related('actor')(仅对User有效)或提前 annotate - 生产环境务必禁用
DEBUG=True,否则actstream的调试日志会额外拖慢响应
最麻烦的其实是时间线去重和分页——stream() 返回的是 QuerySet,但底层是 UNION 多表查询,MySQL 8.0 以下不支持对 UNION 结果直接 LIMIT OFFSET,Django 会全量拉取再切片。这点很容易被忽略,尤其当用户 follow 了上百个项目时。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










