Question

My simplified models are as follows:

class Function(models.Model):
    name = models.CharField(max_length=20)
    params = models.ManyToManyField("Param")

class Param(models.Model):
    name = models.CharField(max_length=20)
    value = models.CharField(max_length=20)

So, every function object has the set of parameters, for example:

f = Function(name="my_function")
f.save()
param1 = Param(name="height", value="100")
param1.save()
param2 = Param(name="width", value="200")
param2.save()
f.params.add(param1)
f.params.add(param2)

The problem is that I cannot figure how to select a function using a filter on function name, parameter name and parameter value.

For above function, the select should be:

Get function with name "my_function" which contains parameter with name "height" and value "100" AND parameter with name "width" and value "200".

Thank you in advance!

Was it helpful?

Solution

This might work:

from django.db.models import Q

functions = (Function.objects
    .filter(name='my_function')
    .filter(Q(params__name='height') & Q(params__value="100")
    .filter(Q(params__name="width") & Q(params__value="200"))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top