Django 在管理中随机排序用户

发布于 2024-09-26 01:40:15 字数 396 浏览 0 评论 0原文

我正在尝试创建一个 Django 管理过滤器,它将获取随机的用户组。此时,我有两个问题:

  1. 将自定义过滤器应用于用户模型,以及
  2. 显示一组随机用户。

在#1 中,我尝试使用 User.username.random_filter = True,但返回时出现 AttributeError,指出 User 没有属性 username

在 #2 上,我知道我可以使用 User.objects.order_by('?')[:50] 获得 50 个随机用户,但我无法弄清楚如何获得结果这样的查询会显示在管理列表中。据我所知,列表是由 URL 的 GET 请求生成的,但我没有用它订购。

有什么建议吗?

I am trying to create a Django admin filter that will get random groups of users. At this point, I have two problems:

  1. Applying a custom filter to the User model, and
  2. Displaying a random set of users.

On #1, I've tried using User.username.random_filter = True, but it comes back with an AttributeError saying that User has no attribute username.

On #2, I know I can get 50 random users with User.objects.order_by('?')[:50], but I have not been able to figure out how to get the result of such a query to show up in the admin listing. As far as I can tell, the listing is generated by the URL's GET request, but I've not had any luck ordering with it.

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦亿 2024-10-03 01:40:15

如果我是您(现在也是),我将停止尝试将此功能与 Django 管理站点集成。根据经验,您会发现您尝试做的事情作为常规视图更容易实现。当然,它没有那么漂亮,但是有用的东西胜过漂亮但不起作用的东西,对吗?

If I were you (and I am), I would stop trying to integrate this functionality with the Django admin site. Speaking from experience, you'll find that what you're trying to do is much easier to implement as regular views. Sure, it isn't be as pretty, but something that works beats something that's pretty but doesn't work, right?

街角卖回忆 2024-10-03 01:40:15

这应该很容易做到,只需创建一个带有 ordering 属性的 ModelAdmin 即可。

像这样的事情应该做:

class UserAdmin(ModelAdmin):
    ordering = ('?',)

It should be fairly easy to do, just create a ModelAdmin with a ordering property.

Something like this should do:

class UserAdmin(ModelAdmin):
    ordering = ('?',)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文