Django ManyToMany filter with more than one condition

被刻印的时光 ゝ 提交于 2019-12-12 01:55:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!