This commit is contained in:
@@ -235,6 +235,29 @@ class VCCourseAdmin(OrderableAdminMixin, ModelAdmin):
|
||||
list_display = ('title', 'course_type', 'price', 'tag', 'instructor', 'lesson_count', 'duration', 'created_at', 'order_actions')
|
||||
search_fields = ('title', 'description', 'instructor', 'tag')
|
||||
list_filter = ('course_type', 'instructor', 'tag')
|
||||
actions = ['reset_ordering']
|
||||
|
||||
@admin.action(description="重置排序 (按ID顺序)")
|
||||
def reset_ordering(self, request, queryset):
|
||||
"""
|
||||
将选中的课程(或全部)按ID顺序重新分配order值
|
||||
"""
|
||||
# 如果没有选中任何项,默认处理所有(Django Admin默认行为是选中了才会触发Action,但为了稳健)
|
||||
# 这里既然是Action,用户必须选中。建议用户选中所有。
|
||||
# 为了方便,如果用户只选了一个,我们可以提示他选更多,或者我们其实可以忽略queryset,直接重置所有?
|
||||
# 通常Action是针对queryset的。
|
||||
# 更好的做法:对选中的queryset按ID排序,然后更新order。
|
||||
|
||||
# 这种实现方式:只重置选中的部分,可能会导致order冲突。
|
||||
# 稳妥方式:重置整个表的排序。
|
||||
|
||||
all_objects = VCCourse.objects.all().order_by('id')
|
||||
for index, obj in enumerate(all_objects, start=1):
|
||||
obj.order = index
|
||||
obj.save(update_fields=['order'])
|
||||
|
||||
self.message_user(request, f"成功重置了 {all_objects.count()} 个课程的排序权重。")
|
||||
|
||||
fieldsets = (
|
||||
('基本信息', {
|
||||
'fields': ('title', 'description', 'course_type', 'tag', 'price')
|
||||
|
||||
Reference in New Issue
Block a user