Count Django objects where two fields are equals

Let's say I have the following Django model:

class Point(models.Model):
    x = models.IntegerField()
    y = models.IntegerField()

I want a count of objects where x == y. I know I can do it in Python:

count = 0
for point in Point.objects.all():
    if point.x == point.y:
        count += 1

However, my table contains millions of records so I want to do this in the database. Is this possible?

Select all Point instances where the x and y are equal and output the count like this:

from django.db.models import F
count = Point.objects.filter(x=F('y')).count()
Back to Top