Skip to content Skip to sidebar Skip to footer

How To Use A Related Manager And Reverse Lookups To Clean Up This Django Queryset

I have some working code, but have recently learned about Related Managers and reverse lookups and would like to know how to apply them to this code: The hacky method I would like

Solution 1:

You can simplify your method like this:

def get_badges_by_type_for_user(self, user):        
    qs = self.get_queryset()
             .select_related('badge', 'badge__badge_type')
             .filter(user=user)
    badges = defaultdict(list)
    for badge_assertion in qs:
        badges[badge_assertion.badge.badge_type].append(badge_assertion.badge)
    return badges

You don't need to iterate over all the BadgeTypes available, but just group the assertions you get, in buckets of badge types. So, not filtration on badge_type is required. Notice the use of defaultdict() here. You can try this out, and see if it works. Haven't tested it myself.

The result structure is different here now. It's:

{
    badge_type1: [badge1, badge2, ...],
    badge_type2: [badge3, badge4, ...]
}

instead of:

[
    {'badge_type' : badge_type1, 'list': [badge1, badge2]},
    {'badge_type' : badge_type2, 'list': [badge3, badge4]}
]

The first one makes more sense here.


Post a Comment for "How To Use A Related Manager And Reverse Lookups To Clean Up This Django Queryset"