gpt4 book ai didi

python - Django 管理操作 : generate actions for all choices with only one method

转载 作者:行者123 更新时间:2023-12-01 08:59:55 25 4
gpt4 key购买 nike

对于如下所示的模型:

class MyModel(models.Model):
my_field = models.CharField(choices=FIELD_CHOICES)

哪里

FIELD_CHOICES = [("Update this", "Update this"),
("Update that", "Update that"),
("Update something else", "Update something else"), ]

并具有以下管理 View

class MyModelAdmin(admin.ModelAdmin):
list_display = ["user", ]

如果我们想要一个操作来更新字段的任何值,我们可以为 ModelAdminView 中的每个值添加一个方法,如下所示:

    actions = ("update_this", "update_that", "update_something_else")

def update_this(self, request, queryset):
queryset.update(my_field="Update this")

def update_that(self, request, queryset):
queryset.update(my_field="Update that")

def update_something_else(self, request, queryset):
queryset.update(my_field="Update something else")

但是,所有这些方法都是相同的,除了一些可以从字段的选择中检索的部分...

Django 是否提供了仅使用一种通用方法即可为字段的所有选择生成操作的方法?

最佳答案

你绝对可以使用 Django 管理员来做这样的事情。我通常通过子类化 get_actions 来实现这一点Django 的 ModelAdmin 类的方法。下面的示例可能不完全是您正在寻找的内容,但至少应该说明一种动态创建任意数量的批量操作的方法,这些操作基本上执行相同的操作:

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):

_update_fields = (
# ('Text for the dropdown', 'a_unique_function_name', 'some value')
('This', 'function_name_for_this', 'this value'),
('That', 'function_name_for_that', 'that value'),
('Other Thing', 'function_name_for_other_thing', 'some other value'),
)

def get_actions(self, request):
def func_maker(value):
# this function will be your update function, just mimic the traditional bulk update function
def update_func(self, request, queryset):
queryset.update(my_field=value)
return update_func

# check out django.contrib.admin.options.ModelAdmin.get_actions for more details - basically it
# just returns an ordered dict, keyed by your action name, with a tuple of the function, a name,
# and a description for the dropdown.
# Python 2.7-style:
actions = super(MyModelAdmin, self).get_actions(request)
# If using Python 3, call it like so:
# actions = super().get_actions(request)

# You can just tack your own values/actions onto it like so:
for description, function_name, value in self._update_fields:
func = func_maker(value)
name = 'update_{}'.format(function_name)
actions['update_{}'.format(function_name)] = (func, name, 'Update {}'.format(description))

return actions

关于python - Django 管理操作 : generate actions for all choices with only one method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com