How to rename only some items in values() in Django?

假如想象 提交于 2020-12-13 03:16:22

问题


Like the title says I need to rename some items in a queryset. The code for the queryset is made like this:

data = SnpsFunctionalelement.objects.values('snpid__rsid', 'elementid__name', 'celllineid__name', 'countexperiments', 'filetype')

i tried to rename the values using from django.db.models import F but if I do

    data = SnpsFunctionalelement.objects.values(rsid=F('snpid__rsid'), FunctionalElement=F('elementid__name'), CellLine=F('celllineid__name'), 
        countexperiments=F('countexperiments'), filetype=F('filetype'))

it gives me an error because countexperiments and filetype are already the names assigned to the model to which they belong. So is there a way to rename only a part of the values of the queryset mantaining the remaining ones?


回答1:


The .values(..) method [Djang-doc] accepts both position parameters (strings of the names of the fields), and named parameters (expressions with alias names). For example:

SnpsFunctionalelement.objects.values(
    'countexperiments',
    'filetype',
    rsid=F('snpid__rsid'),
    FunctionalElement=F('elementid__name'),
    CellLine=F('celllineid__name')
)

Note that, as always in Python, the positional arguments should be placed before the named parameters (since otherwise the "position" is a rather vague concept).



来源:https://stackoverflow.com/questions/57445639/how-to-rename-only-some-items-in-values-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!