Reputation: 1965
I'm returning a json object from my views to my client side.
Thus, in order to keep the code as simple as possible, here is what I do:
def get(self, request, *args, **kwargs):
inspirations = Inspiration.objects.active_translations(get_language()).filter(publish=True)
inspirationsFilter = inspirations.values('translations__title',
'translations__slug', 'categories__translations__name', 'main_image__file')
data = JsonResponse(list(inspirationsFilter), safe=False)
return HttpResponse(data, status=200, content_type='application/json')
But the problem I'm facing here, is this one, from a print with only categories and titles:
[('First Inspiration!', 'category1'), ('Hey max how are you', 'category2'), ('A third inspiration', 'category1'), ('A third inspiration', 'category2')]
As you can see, "A third inspiration" has 2 categories associated, thus it returns the item for each category.
What I would like to have is something similar to:
...('A third inspiration', ['category1', 'category2'])]
categories is a ManyToMany model field created by me, translations is a ManyToMany from django-parler.
Thus, do you know of a solution to "concat" it? Or do I have to do it manually? I've tried values_list but the return is the same.
Edit: until the call to .values, the models query are unique.
Upvotes: 0
Views: 778
Reputation: 169134
You're seeing duplicate rows due to the (implicit) join to the translations table.
This is actually noted in Parler's readme -- so try adding .distinct('id')
.
Upvotes: 2