这是我失败的代码:
dashboard = Dashboard.objects.get(slug=slug)
users = User.objects.all() # list of users
for editor in dashboard.dashboardeditor_set.iterator:
users.remove(editor.user)
错误: 'instancemethod'对象不可迭代
来自models.py:
class DashboardEditor(models.Model):
dashboard = models.ForeignKey(Dashboard)
user = models.ForeignKey(User)
有人可以帮我弄清楚如何从所有用户列表中清除编辑器吗?
谢谢! :)
答案 0 :(得分:2)
我从错误消息中猜到你缺少括号:
for editor in dashboard.dashboardeditor_set.iterator():
这是因为错误消息似乎暗示iterator
在实例方法中,所以你需要调用它来获取实际的迭代器。
答案 1 :(得分:0)
使用values_list()
和exclude()
的组合在单个查询中获取结果(使用嵌套的SELECT
):
dash = Dashboard.objects.get(slug=slug)
User.objects.exclude(id__in=dash.dashboardeditor_set.values_list('user', flat=True))
生成以下SQL:
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user"
WHERE NOT ("auth_user"."id" IN
(SELECT U0."user_id"
FROM "dashboard_dashboardeditor" U0
WHERE U0."dashboard_id" = 1)) LIMIT 21 [0.68ms]
使用iterator
会触发大约N + 2个查询,其中N是给定DashboardEditor
的{{1}}个数:
Dashboard
此示例中有两个In [24]: users = list(User.objects.all())
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user" [0.40ms]
In [25]: for editor in dash.dashboardeditor_set.iterator():
....: users.remove(editor.user)
....:
SELECT "dashboard_dashboardeditor"."id",
"dashboard_dashboardeditor"."user_id",
"dashboard_dashboardeditor"."dashboard_id"
FROM "dashboard_dashboardeditor"
WHERE "dashboard_dashboardeditor"."dashboard_id" = 1 [0.15ms]
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 2 [0.25ms]
SELECT "auth_user"."id",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."password",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."is_superuser",
"auth_user"."last_login",
"auth_user"."date_joined"
FROM "auth_user"
WHERE "auth_user"."id" = 3 [0.24ms]
,ORM运行了4个查询以获取非编辑用户的结果列表。