Skip to content

Instantly share code, notes, and snippets.

@kamyab98
Last active July 17, 2020 09:59
Show Gist options
  • Save kamyab98/5b32e7a814d56ee4f235d9abe8660910 to your computer and use it in GitHub Desktop.
Save kamyab98/5b32e7a814d56ee4f235d9abe8660910 to your computer and use it in GitHub Desktop.
class PublisherCategoriesListAPIView(generics.ListAPIView):
serializer_class = PublisherCategorySerializer
queryset = Publisher.objects.all().values('id')
def get_serializer_context(self):
ctx = super().get_serializer_context()
publishers = Publisher.objects.all().values('id', 'name', 'category_membership__category_id')
publishers_dict = {}
for publisher in publishers:
if publishers_dict.get(publisher['id']) is None:
publishers_dict[publisher['id']] = {
'publisher_id': publisher['id'],
'name': publisher['name'],
'categories': set(),
}
if publisher['category_membership__category_id']:
publishers_dict[publisher['id']]['categories'].add(publisher['category_membership__category_id'])
ctx['data'] = publishers_dict
return ctx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment