filter queryset on the basis of related queryset length

is there any ways to filter queryset on the basis of related queryset length?
for example, I wanna get all objects which foreignKey field (it would be a queryset) is not empty.
so, how can I filter objetcs like this: Something.objects.filter(foreignkeyfield__lenght__gte=1)
When I try this, django says, that there is not lookup like “lenght”.

To make sure I’m clear -

You’ve got a class, let’s call it BaseModel.
There’s another model, called RelatedModel with a ForeignKey field referencing BaseModel.

The query you’re trying to resolve is to find all BaseModel for which there are no RelatedModel instances referencing it.

Is this correct?

If so, your query would be:

BaseModel.objects.filter(relatedmodel=None)

You can also use:
BaseModel.objects.filter(relatedmodel__isnull=True), which also has the complementary query BaseModel.objects.filter(relatedmodel__isnull=False) which returns only those BaseModel objects having RelatedModel objects referring to them.

(Side note: the word is “length”, not “lenght” - if there were a field lookup named “length”, this would matter.)

1 Like

While I suspect Ken is right considering your code is using __gte=, I want to point out that you can use the Count() aggregate expression to determine the exact number of related model instances.

Here’s some example code.

from django.db.models import Count

somethings = Something.objects.annotate(
    foreignkey_count=Count('foreignkeyfield')
)

# You can filter on the annotated field now:
somethings_with_five_fks = somethings.filter(foreignkey_count__gte=5)

There’s more information on this part of the ORM here: Query Expressions | Django documentation | Django

1 Like