[Answer]-Django: Filter for many to many field gives too many answers?

1👍

Your objective:

Now I want to get all the dose measurements from the Measurement model for a specific Linac and Energy.

My approach:

  1. Get the Linac record.
  2. Use the many-to-many link table to get the appropriate Energy record.
  3. Get all MeasurementConfig records linked to the Linac record.
  4. For each MeasurementConfig records, get all Measurement records; use the Energy record to filter this record set.

In the code you posted, it looks like you’re trying to filter the Measurements record set on a link that doesn’t exist, according to the models you specified.

# Get the measurements
energymeasurements = []    
for energy in energies:
    measurements = Measurement.objects.filter(config__linac=linac).filter(config__linac__energies__exact=energy)
    energymeasurements.append(measurements)

A Measurement isn’t linked to a Linac, so I think this is why you’re not getting the result you expect.

👤Mike P

Leave a comment