在我的ModelAdmin中,我计算了两个聚合值,并希望显示带有小部件的值。
def get_queryset(self, request):
qs = super(QuizAdmin, self).get_queryset(request).annotate(
avg_difficulty=Avg('ratings__difficulty'),
avg_rating=Avg('ratings__rating'),
)
return qs.filter(author__agents=request.user)
目前我正在这样做
def avg_difficulty(self, obj):
return StarRatingWidget().render(attrs={'id': 'id_avg_difficulty'},name="avg_difficulty", value=obj.avg_difficulty, readonly=True)
是否有更简单,更灵活的方法将小部件用于聚合值?在ModelForm中注册似乎不起作用。
答案 0 :(得分:1)
这是正确的方法,但是,如果您的窗口小部件仅用于此案例,则您甚至不需要窗口小部件。例如,您可以这样做:
from django.utils.html import format_html
class MyModelAdmin(admin.ModelAdmin):
readonly_fields = ['avg_difficulty']
def avg_difficulty(self, obj):
return format_html(
('<span id="id_avg_difficulty" class="rater" '
'data-value="{}"></span>'), obj.avg_difficulty)
avg_difficulty.short_description = "Average difficulty"