Django ManyToMany filter with more than one condit

2019-08-20 05:28发布

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!

1条回答
再贱就再见
2楼-- · 2019-08-20 06:16

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"))
查看更多
登录 后发表回答