如何在Django中仅重命名values()中的某些项目? [英] How to rename only some items in values() in Django?

查看:63
本文介绍了如何在Django中仅重命名values()中的某些项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题一样,我需要重命名查询集中的某些项目.queryset的代码如下所示:

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

我尝试使用django.db.models import F 中的重命名值,但如果我这样做

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

这给我一个错误,因为 countexperiments filetype 已经是分配给它们所属模型的名称.那么,有没有办法只重命名一部分查询集的值来保留其余的值呢?

解决方案

请注意,像在Python中一样,位置参数应放置在命名参数之前 (因为否则位置"是一个相当模糊的概念)./p>

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?

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).

这篇关于如何在Django中仅重命名values()中的某些项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆