开发者

Django - many-to-one relationship - how to select parent models that have children only

开发者 https://www.devze.com 2023-02-05 14:38 出处:网络
Say I have this model relationship in 开发者_运维百科Django 1.2... class Section(models.Model):

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消