问题
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:
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"))
来源:https://stackoverflow.com/questions/7883391/django-manytomany-filter-with-more-than-one-condition