如何限制在 Django 管理站点中查看的查询集/记录?

发布于 2024-08-22 01:04:49 字数 57 浏览 4 评论 0原文

默认情况下,Django 管理站点显示相关模型/表的所有记录以供查看。如何只显示符合特定条件的记录?

By default Django admin site shows all records of a related model/table for viewing. How can I show only the records that meet certain criteria?

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

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

发布评论

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

评论(2

薄情伤 2024-08-29 01:04:49

在管理员定义中,您可以定义一个 queryset() 方法,该方法返回该模型管理员的查询集。例如:

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.filter(user=request.user)

那么只有带有 user=request.user 的对象才会在管理中可见。

In your admin definition, you can define a queryset() method that returns the queryset for that model's admin. eg:

class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        return qs.filter(user=request.user)

Then only objects with user=request.user will be visible in the admin.

玩心态 2024-08-29 01:04:49

我知道这有一个“可接受的答案”,但我只是想把它扔在那里,因为我在追求其他东西时遇到了这个答案,并意识到我有一个我发现并经常使用的替代解决方案,它给了我比它更精细的级别控制接受的答案。

class TestAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "FIELD":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "FIELDS":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

I know this has an "accepted answer", but I just wanted to throw this out there since I came across this answer while pursuing something else and realized I had an alternative solution that I found and use often that gives me more granular level control than the accepted answer.

class TestAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "FIELD":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "FIELDS":
            kwargs["queryset"] = TestModel.objects.filter(test=False)
        return super(TestAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文