Django advanced queries -


i have 3 models: pupils, instructor, group. connected through pupils model so:

class pupils(models.model):     instructor = models.foreignkey(instructor, blank=true, default=none, null=true)     group = models.foreignkey(group, default=none, null=true, blank=true) 
  1. how write property group model returns instructors have pupils current group? best can find instructors have pupils:

    @property def instructors(self):     pupils.models import instructor     return list(instructor.objects.filter(pupils__isnull=false).values()) 
  2. how count number of pupils current group each instructor?

i have 3 models: pupils, instructor, group. connected through pupils model so:

this means have m2m relation between instructor , group can define this:

class instructor:     #...     groups = models.manytomanyfield(group, through='pupils') 

now using m2m relation, can take instructor groups this:

instructor.groups.all() 

you can use reverse relation of m2m relation in order instructors group.

group.instructor_set.all() 

you can instructors count using .count()

#group instructors count group.instructor_set.count() #or if want count pupils,  #use reverse relation of foreignkey #group.pupils_set.count() 

now 2nd part of question if understand correctly need this:

#this give instructors of group pupils count. group.instructor_set.annotate(pupils_count=count('pupils')) 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -