3👍
✅
Many-to-Many relationships are mutual. So stores can be seen from brands and vice-versa.
You can use prefetch_related
to minimize the number of DB queries that will be required to do this:
brands = Brand.objects.filter(slug=slug).prefetch_related('stores')
stores = [b.stores.all() for b in brands] # all related stores to those brands
Update
related_name
was not properly defined. Use the name of the model that contains the M2M relationship:
brands = models.ManyToManyField('Brand', related_name='stores')
-1👍
I think I’ve found a solution online, not sure if it’s perfect but it’s working for me:
class Store(models.Model):
brands = models.ManyToManyField('Brand', blank=True)
class Brand(models.Model):
stores = models.ManyToManyField('Store', through=Store.brands.through, blank=True)
👤Ryan
- [Answered ]-Linking the View / Model in Django to a Javascript Front End Framework
- [Answered ]-Django DetailView with form for comments
- [Answered ]-AngularJS request.POST return QueryDict: {}
- [Answered ]-Deploying django project on apache
Source:stackexchange.com