Django - 添加 类 仅当 qs len 大于 5 时内联

Django - Add classes to inline only if qs len is more than 5

对于 TaskInline 如果元素超过 5 个,我想折叠显示:

from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models


class Task(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField()
    performer = models.ForeignKey(User, on_delete=models.CASCADE)


class TaskInline(admin.TabularInline):
    model = Task

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if len(qs) > 5:
            self.classes = 'collapse',
        return qs


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    inlines = TaskInline,

但是在 get_queryset 方法中实现的技巧似乎不起作用(似乎此方法选择了 Task 模型的所有项目)。

我应该在哪里比较len来添加classes

没有 “合适的” 方法,但是...要实现您想要的效果,您可以选择任何接受 obj 参数的方法。像 has_view_permissionget_formsget_formsetget_extra...

请注意,您不会收到相关经理的 QuerySet,而是会收到 non-inline 管理员中要求的 obj

示例:


class TaskInline(admin.TabularInline):
    model = Task

    def has_view_permission(self, request, obj=None, **kwargs):
        # None for new instances or non object-specific calls
        if obj is not None:  
            # print(obj) -> instance that has Task as inline
            # TODO: fix the following line, because your field might be called differently
            if obj.tasks.count() >= 5:  
                self.classes = list(type(self).classes or []) + ["collapse"]
        return super().has_view_permission(request, obj=obj, **kwargs)