On Fri, May 22, 2009 at 8:21 PM, Patrick <whya...@gmail.com> wrote:

>
> Do I also need to use select_related() anywhere?
>
> On May 22, 5:57 pm, Alex Gaynor <alex.gay...@gmail.com> wrote:
> > On Fri, May 22, 2009 at 7:41 PM, George Song <geo...@damacy.net> wrote:
> >
> > > On 5/22/2009 5:31 PM, Patrick wrote:
> > > > What is the best way to make queries on a manytomany table?
> >
> > > > Given the models below, how can I get a list of all the songs a
> > > > particular artist has?
> >
> > > > class Artist(models.Model):
> > > >     name = models.CharField(max_length=128)
> >
> > > >    def __unicode__(self):
> > > >         return u'%s' %(self.name)
> >
> > > > class Album(models.Model):
> > > >     title = models.CharField(max_length=128)
> > > >     artists = models.ManyToManyField(Artist)
> >
> > > >     def __unicode__(self):
> > > >         return u'%s' %(self.title)
> >
> > > > class Song(models.Model):
> > > >     title = models.CharField(max_length=128)
> > > >     albums = models.ManyToManyField(Album)
> >
> > > >     def __unicode__(self):
> > > >         return self.title
> >
> > > Probably a compound query:
> >
> > > 1. All albums for a given artist
> > > 2. All songs where albums in #1
> >
> > > --
> > > George
> >
> > Song.objects.filter(albums__artists=<some_artist_obj_or_pk>)  will do
> what
> > you want.
> >
> > You might need to put distinct on this to prevent duplicate items.
> >
> > Alex
> >
> > --
> > "I disapprove of what you say, but I will defend to the death your right
> to
> > say it." --Voltaire
> > "The people's good is the highest law."--Cicero
> >
>
No, select_related is a) exclusively an optimization, it doesn't affect the
results you see, and b) it pulls in related objects via foreign keys, so
even if you might want it here for optimization purposes it wouldn't have
any affect since you don't have any foreign keys.

Alex

-- 
"I disapprove of what you say, but I will defend to the death your right to
say it." --Voltaire
"The people's good is the highest law."--Cicero

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to