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) how write property
groupmodel returnsinstructors 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())- how count number of
pupilscurrentgroupeachinstructor?
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
Post a Comment