开发者

Is there a faster way to do this?

开发者 https://www.devze.com 2023-04-12 08:39 出处:网络
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...

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

精彩评论

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

关注公众号