Jim
Jim

Reputation: 97

Django get related foreignkey count (Distinct)

i want to get count of related foreignkey values like this;

Assume that, the value table of this

GAME        STATUS
GAME1         FINAL
GAME2         FINAL
GAME3         PLAYOFF
GAME4         FINAL

I want to show how many different situations (the result from the table above should be 2)

models.py

class Game(models.Model):
    gamestatus = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)

class Status(models.Model):
    name...

Upvotes: 2

Views: 627

Answers (2)

ruddra
ruddra

Reputation: 51978

You can try like this using distinct:

Game.objects.values('gamestatus').distinct().count()

Upvotes: 3

Alex Antonov
Alex Antonov

Reputation: 15146

Try F() annotation:

from from django.db.models import F

Game.objects.annotate(status=F("status__name"))

Upvotes: 0

Related Questions