Dave Reed
Dave Reed

Reputation: 23

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?

Upvotes: 0

Views: 1371

Answers (2)

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16346

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.

Upvotes: 2

zs2020
zs2020

Reputation: 54514

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)

Upvotes: 2

Related Questions