请有人纠正我,但我想至少在我自己的情况下,我已经找到了解决方案。
我想处理所有属性完全等于...的元素。
但是我有几个模型,这个例程应该适用于所有模型。 它确实:
def selectByProperties(modelType, specify):
clause = "SELECT * from %s" % modelType._meta.db_table
if len(specify) > 0:
clause += " WHERE "
for field, eqvalue in specify.items():
clause += "%s = '%s' AND " % (field, eqvalue)
clause = clause [:-5] # remove last AND
print clause
return modelType.objects.raw(clause)
通过这个通用子例程,我可以选择与我的“ specify”(属性名称,属性值)组合的字典完全相等的所有元素。
第一个参数采用(models.Model),
第二个字典像:{“ property1”:“ 77”,“ property2”:“ 12”}
它创建了一个SQL语句,例如
SELECT * from appname_modelname WHERE property1 = '77' AND property2 = '12'
并在这些元素上返回QuerySet。
这是一个测试功能:
from myApp.models import myModel
def testSelectByProperties ():
specify = {"property1" : "77" , "property2" : "12"}
subset = selectByProperties(myModel, specify)
nameField = "property0"
## checking if that is what I expected:
for i in subset:
print i.__dict__[nameField],
for j in specify.keys():
print i.__dict__[j],
和? 你怎么看?