Django - many-to-one relationship - how to select parent models that have children only
Say I have this model relationship in 开发者_运维百科Django 1.2...
class Section(models.Model):
title = models.CharField(max_length=200)
class Page(models.Model):
section = models.OneToOneField(Section)
title = models.CharField(max_length=200)
I want to select Sections that have one or more Pages associated with them, how would I achieve this in a query? Or would I have to select all sections and then filter out one's that do not have pages manually?
Change to:
class Section(models.Model):
title = models.CharField(max_length=200)
page = models.ForeignKey(Page, related_name="section")
class Page(models.Model):
title = models.CharField(max_length=200)
select Sections that have one or more Pages associated:
result_q = Section.objects.filter(page__isnull=False)
I would second sza's answer if was 100% sure that isnull
works in all such cases - but I haven't checked that so I'm not sure (even though I occasionaly use it for such purposes) :-)
What I'm sure of is this:
from django.db import models
Section.objects.annotate(page_num=models.Count('page')).filter(page_num__gt=0)
-- and while counting might be an overkill for your case wih OneToOneField relationship, it definitely works.
精彩评论