python - Django: Filter for many to many field gives too many answers? -
have following 4 models
measurement:
class measurement(models.model): config = models.foreignkey(measurementconfig) energy = models.foreignkey(energy) dose = models.decimalfield(max_digits=20,decimal_places=9, blank=true, null=true)
measurementconfig
class measurementconfig(models.model): date = models.datetimefield(auto_now_add=true) linac = models.foreignkey(linac)
linac
class linac(models.model): name = models.charfield(max_length=10) genre = models.foreignkey(type) energies = models.manytomanyfield(energy)
energy
class energy(models.model): value = models.positiveintegerfield() category = models.foreignkey(energycategory)
now want dose measurements measurement model specific linac , energy.
i have used following code these:
linac = get_object_or_404(linac, name=linacname) # energies specified linac measurementconfigs = measurementconfig.objects.filter(linac=linac) identifications = [] measurementconfig in measurementconfigs: identifications.append(measurementconfig.identification) config = get_object_or_404(measurementconfig, identification=identifications[0]) energies = config.linac.energies.all() # measurements energymeasurements = [] energy in energies: measurements = measurement.objects.filter(config__linac=linac).filter(config__linac__energies__exact=energy) energymeasurements.append(measurements)
what expect energymeasurements like this:
energymeasurements = [(measurements_**energy1**), (measurements_**energy2**), (measurements_**energyn**)]
where n amount of energies
but this:
energymeasurements = [(measurements_**allenergies1**), (measurements_**allenergies2**), (measurements_**allenergiesn**)]
where n amount of energies.
so expect query make gets measurements specific energy specified loop. instead measurements energies. i've tried without loop using id of specific energy, same problem occurs.
i know problem in query, can't find out is.
your objective:
now want dose measurements measurement model specific linac , energy.
my approach:
- get linac record.
- use many-to-many link table appropriate energy record.
- get measurementconfig records linked linac record.
- for each measurementconfig records, measurement records; use energy record filter record set.
in code posted, looks you're trying filter measurements record set on link doesn't exist, according models specified.
# measurements energymeasurements = [] energy in energies: measurements = measurement.objects.filter(config__linac=linac).filter(config__linac__energies__exact=energy) energymeasurements.append(measurements)
a measurement isn't linked linac, think why you're not getting result expect.
Comments
Post a Comment