Quick Django Trick

Recently while playing around with a Django model in the always awesome iPython shell I discoved a neat feature of the Django ORM.  It's basically a way to get the id of a related object without actually triggering a query to get all of the related object's data.

Frequently when working with a model which has a foreign key, I simply want to access the id of the related item and I don't care about any of the related item's other information.  Situations where this comes up include generating links and building queryset filters.  Unfortunately if I follow the normal Django style and do something like "item.related.id", the Django ORM will fire off an extra query to get all of the information of the related object (which I don't care about).  While this is far from tragic it is still unnecessary work since all I care about is the object's id and that is already contained in the "item" object.

Fortunately there is an alternative!  Instead of getting the id via "item.related.id" one can say "item.related_id".  Using this method, no extra query is performed and I get just the id value I was looking for.

There are two things to be aware of with this trick.  First I have not found this feature documented anywhere with a cursory search of the Django docs.  This means that I am not sure how much this feature is actually supported and how permament it may or may not be.  Second while I have not tested it, I suspect that if your foreign key has a custom database field name, the field on the model will match that custom field name.

As I come across any other quick Django tricks I may start making them a regular feature here on the blog.  If you found this intersting or have your own quick django trick, let me know and leave a comment!