[Answered ]-How to get data from both sides of a many to many join in django

1👍

Building up on your second attempt using Well, you will have to prefetch WellConditionAntibiotic and also select the related antibiotic like this:

from django.db.models import Prefetch


well = Well.objects.filter(pk=1).prefetch_related(
    Prefetch(
        "well_condition_antibiotics",
        queryset=WellConditionAntibiotic.objects.select_related("antibiotic"),
    )
)

Then you can just iterate through the related WellConditionAntibiotic entries with the corresponding antibiotic:

for well_condition_antiobiotic in well.well_condition_antibiotics.all():
    print(well_condition_antiobiotic.antibiotic.name)

You can find more information about prefetch_related and Prefetch here..[Django-doc]

Leave a comment