Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django管理列表视图在自定义列中显示外部url数据_Django_Django Admin - Fatal编程技术网

Django管理列表视图在自定义列中显示外部url数据

Django管理列表视图在自定义列中显示外部url数据,django,django-admin,Django,Django Admin,我们有一个列表视图,如下所示 现在假设我们想在视图中添加一个模型中不存在的列。所以我们可以通过在admin类中创建一个方法来实现这一点 class PageAdmin(admin.ModelAdmin): list_display = ["id", "title", "slug", "author", 'updated', 'custom_field'] def custom_field(self, obj): # logic... retu

我们有一个列表视图,如下所示

现在假设我们想在视图中添加一个模型中不存在的列。所以我们可以通过在admin类中创建一个方法来实现这一点

class PageAdmin(admin.ModelAdmin):

    list_display = ["id", "title", "slug", "author", 'updated', 'custom_field']

    def custom_field(self, obj):
        # logic...
        return True # or False based on above logic
这很简单。 现在让我们看一个更复杂的场景,我需要根据goodreads.com搜索结果填充此列。 我的意思是,我会在goodreads上搜索对象
title
,找到准确的标题,如果找到,则返回True,否则返回False

例如,有一个页面对象,它的标题是《饥饿游戏》,所以当我搜索它时,我会得到

我将解析结果并检查前10个结果中是否存在确切的标题

class PageAdmin(admin.ModelAdmin):

    list_display = ["id", "title", "slug", "author", 'updated', 'custom_field']

    def custom_field(self, obj):
        # search on goodreads.com, parse results and match with obj.title
        return True # or False based on above logic
这种方法的问题是,它使管理员页面非常慢。。因为它将获取页面中所有对象的数据(通常为100个对象)

我该如何改进这一点?有没有异步的方法可以做到这一点,而不需要改变太多的html/css/js。 对于我的用例,如何在admin类中使用changelist\u view方法

PS:我也会考虑批量搜索方法,如果它是一个不同的领域。我的意思是,我将只点击一次并传递所有对象的标题(逗号分隔),而不是点击搜索api 100次。

假设这将只返回完全匹配的书籍,并且基于id,我可以在管理页面上显示True或False

PPS:我无法在db表中添加其他列,如果外部服务关闭或响应时间过长,我将显示一些相关消息

class OrderAdmin(admin.ModelAdmin):

    list_display = ["id", "title", "slug", "author", 'updated', 'custom_field']

    def custom_field(self, obj):
        return obj.title in self.found_in_goodreads

    def get_paginator(self, *args, **kwargs):
        paginator = super().get_paginator(*args, **kwargs)
        request, queryset, count = args
        page = int(request.GET.get('p', 1))  #  For current page only
        titles = paginator.page(page).object_list.values_list('title', flat=True)

        # search_goodreads
        # url = "https://api.goodreads.com/search?query={}".format(''.join(titles))
        # response = requests.get(url)
        # parse the response and store titles in the list
        # self.found_in_goodreads = [title for titles in response]
        return paginator
此外,您必须处理goodreads服务器停机、返回400、超时等情况