简体   繁体   中英

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. 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. The context processor function is as below.

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.

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:

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

To get a simple distinct list of different versions, you probably want flat=True, ie

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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