Tip: How to get a single object`s value with Django ORM

Posted on Wed 11 November 2015 in Programming • Tagged with django, python, ormLeave a comment

There are times when you want to get a single field of a single object in the database. For example, just get the headline of the blog post #1, not fetching it’s body. How do you do it in a usual way?

:::python
>>> BlogPost.objects.only('headline').get(pk=1).headline
'Hello world'

# Or maybe even this way:
>>> BlogPost.objects.values('headline').filter(pk=1)[0]['headline']
'Hello world'

Recently I’ve stumbled upon a shorter one:

Continue reading