On 10/25/06, Christian Joergensen <[EMAIL PROTECTED]> wrote:
> Daniel Roseman wrote:
> >>> Country.objects.all().extra(
> >>>     where=['(SELECT COUNT(*) FROM appname_soccerteam WHERE
> >>> appname_soccerteam.country_id = appname_country.id) > 0']
> >>> )
> >> Great idea! I did not think about the 'extra' method. Works perfectly.
> >> Gave me a speedup factor of about 250k :)
> >>
> >> Thanks,
> >
> > Alternatively you could use the normal django syntax:
> > Country.objects.filter(soccerteam__name__isnull=False)
>
> But the thing is, I can have multiple SoccerTeam relations. Doesn't that
> rule out this solution?

You can use distinct():

Country.objects.filter(soccerteam__name__isnull=False).distinct()

Country won't have a soccerteam attribute - by default, it will have a
soccerteam_set attribute. If you add a related_name argument to the
ForeignKey in the SoccerTeam class, you can change the name of this to
whatever you want.

class SoccerTeam(models.Model):
    ...
    country = models.ForeignKey(Country, related_name='soccerteams')
    ...

Country.objects.filter(soccerteams__id__isnull=False).distinct()

I'd guess the INNER JOIN the ORM for you (the check for a particular
field being null is bogus in this case - it's the join which does the
work for you) would be faster than the COUNT.

Jonathan.

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to