Lets say we have the following models: (simplified)
class Collection(models.Model):
slug = models.SlugField()
class Brochure(models.Model):
collection = models.ForeignKey(Collection)
class Page(models.Model):
brochures = models.ManyToMany(Brochure)
- There are 2 collections ‘x’ and ‘y’.
- A page has a selection of brochures, not all.
Is there a way to get a dictionary of brochures like this:
{'x': [brochure1, brochure2], 'y': [brochure3, brochure4]}
only by using the many-to-many manager:
page_instance.brochures.all()
EDIT
I want to work with the brochures related to Page. Not Brochures.objects.all() or collection_instance.brochure_set. That’s why I included Page.
I found defaultdict, which helps me do this:
collection_brochures = defaultdict(list)
for b in self.brochures.all():
collection_brochures[b.collection.slug].append(b)
Actually this is the answer to my question.
I can work with this, but ideal would be a list with dicts like this:
[{'collection': 'x', 'brochures': [brochure1, brochure2]}, {'collection': 'y', 'brochures': [brochure3, brochure4]}]
I hope this code snippet will do the job.
Also you can use model instances as keys, so if you wish to see
Collectioninstances instead of their slugs, you may replace third line with this one:This will give you following data: