On 07/03/06, Russell Keith-Magee <[EMAIL PROTECTED]> wrote:
> > class Topic (models.Model ):
> > parent = models.ForeignKey('self', null=True, blank=True,
> > related_name='child')
> > title = models.CharField(maxlength=128)
> > description = models.TextField()
> >
> > class Article (models.Model ):
> > topic = models.ManyToManyField(Topic)
> > title = models.CharField(maxlength=255)
> > body = models.TextField()
> >
> > Is it possible in a single line to retrieve all Topics that have at
> > least 1 related article without manually iterating through the Topics
> > to find out?
>
> At present, there isn't an 'exists' operation for queries - although it
> sounds like a good addition. It would probably end up as part of aggregate
> functionality, so it might be worth adding a note to ticket 1435 so your
> idea doesn't get forgotten.
I think I'm that much of a noob that I'm not too sure what idea it is
I've had! So if it's a good idea perhaps you could add it to the
ticket or explain it to me? :)
> However, in the interim, something like:
>
> Topic.objects.filter(article_set__id__notnull=True).distinct()
> might do the trick. It's a slightly roundabout way of getting it done - the
> article_set__id__notnull is there to deliberately select every row of the
> article_set; by putting this query in the Topic filter, it forces an inner
> join from Topic to Article, which contains every member of article; because
> the query is over Topic, only topic columns are returned, so enabling
> distinct should give you one result for every Topic that has at least one
> Article.
Thanks a lot for that, worked perfectly with a slight modification to
the syntax:
Topic.objects.filter(article__id__isnull=False).distinct()
Steve
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---