Answer the question
In order to leave comments, you need to log in
How to compose a query from 3 tables in Django ORM?
There is a training database from 3 tables. Country, clubs and fans of clubs.
class Country(models.Model):
title = models.CharField(max_length=20)
strength = models.IntegerField('Численность')
def __str__(self):
return self.title
class Club(models.Model):
title = models.CharField(max_length=20)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Fun(models.Model):
name = models.CharField(max_length=15)
club = models.ForeignKey(Club, on_delete=models.CASCADE)
def __str__(self):
return self.name
Club.objects.annotate(c=Count('fun')).filter(c__gt=<n>).annotate(total=Count('title', distinct=True)).values('country__title', 'total')
sub = Club.objects.filter(country=OuterRef('pk')).annotate(c=Count('fun')).filter(c__gt=<n>).annotate(total=Count('title', distinct=True)).values('total')
x = Country.objects.annotate(result=Subquery(sub[:1]))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question