Tuesday, March 1, 2011

Re: Accessing foreign key fields

The reason to use the 2) is to be able access the full info of the user author model. 
If you are interested in showing more than just the author_id then you should use the article.author (the .id is comes attached :P )

N.

On Tue, Mar 1, 2011 at 6:41 PM, ydjango <traderashish@gmail.com> wrote:
In second one- article.author.id, django does a DB lookup to get
author object and then id is attribute of author.
In first article.author_id : author_id is direct attribute of article
(actually a foreign key field which django generates).  Requires one
less DB lookup

values both way are same. Performance is not.


On Mar 1, 3:11 am, Ankit Rai <i.ankit....@gmail.com> wrote:
> I am not getting what is difference between the 1 & 2?Can anyone tell me the
> difference
>
>
>
> On Tue, Mar 1, 2011 at 9:16 AM, ydjango <traderash...@gmail.com> wrote:
> > 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.
>
> --
>
> *Ankit Rai*
>
> *
> *

--
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.




--
Norberto Leite

--
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