开发者

Is there a faster way to do this?

I o开发者_JAVA百科ften want to grab one field from one table. So I do this:

tmp = my_model.objects.get(pk=5) //Or some other record...
myVar = tmp.myField

Now myVar holds the value I want. This two step process is annoying. Is there a one step way of doing this?

Thanks


myVar = my_model.objects.get(pk=5).myField


Since you're only concerned about one field, I'd recommend:

myVar = my_model.objects.values('myField').get(pk=5)['myField']

No need to put undue load on your DB.


myVar = my_model.objects.filter(pk=5).values_list('myField', flat=True)[0]

Personally I see above as the most elegant way. It will select only myField from database and pass it to myVar

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜