Andrii Rusanov
Andrii Rusanov

Reputation: 4606

Get entries by values in child model

I have a following model:

class Parent(models.Model):
    title = models.CharField(max_length=255)


class Child(models.Models):
    title = models.CharField(max_length=255)
    parent = models.ForeignKey(Parent)

How can I get all entries from Parent, where count of Child equal 0? I need to do it throught Parent model, something like this:

 Parent.objects.filter(smth_condition)

Upvotes: 0

Views: 106

Answers (2)

Pavel Anossov
Pavel Anossov

Reputation: 62908

. from django.db.models import Count

Parent.objects.annotate(cc=Count('child')).filter(cc=0)

Per-object summaries can be generated using the annotate() clause. When an annotate() clause is specified, each object in the QuerySet will be annotated with the specified values.

In a way similar to Lookups that span relationships, aggregations and annotations on fields of models or models that are related to the one you are querying can include traversing “reverse” relationships. The lowercase name of related models and double-underscores are used here too.

Annotated values can also be filtered. The alias for the annotation can be used in filter() and exclude() clauses in the same way as any other model field.

Another way, which may be more effective depending on your tables, is simply

Parent.objects.filter(child=None)

Upvotes: 2

okm
okm

Reputation: 23871

Also try

Parent.objects.filter(child=None)
# or
Parent.objects.filter(child__isnull=True)

Upvotes: 1

Related Questions