Monday, February 28, 2011

Accessing foreign key fields

class Article(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length = 100)

(assume an article can have only one author)

article = Article.objects.get(title="Django is awesome)

if I need only author id, I can access author id as 1)
article.author_id or 2) article.author.id

I prefer first article.author_id as it requires less db lookup and
hence better performance.

Any reason to use 2nd way over 1st.

( I understand this approach only works for id and not for say author
name)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment