[Answered ]-Access many to many field from queryset Django

1👍

Since wr is a list of WineRegions, you need to iterate through them first:

vineyardList = []
for wr in WineRegion.objects.filter(id__in=id_list):
    for vineyard in wr.vineyards.all():
        vineyardList.append(vineyard)

But this will hit your db multiple times just to get each vineyard objects. Instead, you can access the related name wineregion from Vineyard to get all the vineyard objects in one query like this:

vineyardList = Vineyard.objects.filter(wineregion__in=WineRegion.objects.filter(id__in=id_list))

or simply:

vineyardList = Vineyard.objects.filter(wineregion__in=id_list)

Leave a comment