On Fri, 2006-07-07 at 12:16 +0200, Kilian CAVALOTTI wrote: > Hi all, > > I have a question about reverse queries in ForeignKey relationships. Taking > the example given in > <http://www.djangoproject.com/documentation/models/many_to_one/>, I know that > I can filter the Reporter objects to get those who have associated Articles, > based on Article properties: > > Reporter.objects.filter(article__headline__startswith='This') > > I guess I can get all Reporters who have associated Articles by doing: > > Reporter.objects.filter(article__isnull = False) > > > But, is there a way to get Reporters who have *no* associated Article? I tried > > Reporter.objects.filter(article__isnull = True) > > but it returns an empty list, since the article property does not exist for > those Reporters, and thus, it can't even be null. > > The aim is to use this in a limit_choices_to option, to only allow selection > of 'free' Reporters in the admin interface (ie. Reporters who still do not > have written any article, they lazy guys).
This is a very interesting question. The answer is kind of hinted at in the documentation (it's the reverse of creating an empty relation set), but I only realised that after messing around at the interactive prompt a little to work out the answer. Reporter.objects.filter(article = None) will give you the list you want. I'll add something to the documentation to make this more explicit once I work out how to phrase it. Best wishes, Malcolm --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---