简体   繁体   English

从表中获取列作为数组在网页上使用 context_processor

[英]Getting column from table as an array to using context_processor on webpage

I am trying to pull column data from DB table using a Django context_processor.我正在尝试使用 Django context_processor 从数据库表中提取列数据。 This table column contains different versions of the primary data.此表列包含不同版本的主要数据。 So need to collect all versions and pass it as context to the html page.因此需要收集所有版本并将其作为上下文传递给 html 页面。 The context processor function is as below.上下文处理器 function 如下。

I am able to get all the versions, but the format is weird.我能够获得所有版本,但格式很奇怪。 Any idea how to clean and only get the versions in an array?知道如何清理并仅获取数组中的版本吗? There are 2 versions currently Version1.9 and Version2.0 in the Column.专栏目前有2个版本Version1.9和Version2.0。

context_processor.py context_processor.py

def Version(request):
    value = ModelName.objects.values_list('version')

    if value:
        return { 'getVersion' : value }
    else:
        print("Unable to get Version")
        return { 'getVersion' : "" }

Console Output:控制台 Output:

<QuerySet [('Version1.9',), ('Version2.0',), ('Version1.9',), ('Version2.0',)]>

To get a simple distinct list of different versions, you probably want flat=True, ie要获得不同版本的简单不同列表,您可能需要 flat=True,即

value = ModelName.objects.values_list('version', flat=True)

That converts it from a queryset of multiple tuples to just an array of values.这会将其从多个元组的查询集转换为一个值数组。

Now, that doesn't de-duplicate it for you, but you can sort that out by converting it to a set.现在,这不会为您删除重复数据,但您可以通过将其转换为集合来对其进行排序。

versions = set( ModelName.objects.values_list('version', flat=True) )
value = ' '.join(versions)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM