2015-01-13 8 views
2

나는 내가 ContentType 모델에서 가져온 app_labelmodel 키 사전의 목록을 가지고 :목록에서 결합 된 Q 개체를 생성하는 방법은 무엇입니까?

model_list = [ 
    { 
     'app_label': 'store', 
     'model': 'product', 
    }, 
    { 
     'app_label': 'store', 
     'model': 'profile', 
    }, 
] 

나는 ForeignKey.limit_choices_to argument으로 사용이에서 결합 Q objects 세트를 생성해야합니다. 이것은 내가 출력 필요가있다 :

limit = Q(app_label = 'store', model = 'product') | Q(app_label = 'store', model = 'profile') 

그래서 나는이 같은 모델에서 사용할 수 있습니다 :

class Review(models.Model): 
    content_type = models.ForeignKey(ContentType, limit_choices_to = limit) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 
    # ... 

누구나 통해 반복하여 | 연산자와 결합 Q 객체의 목록을 작성하는 방법을 알고 이 사전 목록?

답변

1

operator.or_ (또는 lambda a, b: a | b)와 reduce 사용 :

limit = reduce(operator.or_, (Q(**condition) for condition in model_list)) 
+0

왜 우리가'사용할 수 없습니다 |'대신'operator.or_'의를? –

+1

@mu 無,'|'는 피연산자가 필요합니다 (oeprator, oeprator.or_와 같은 함수가 아닙니다). 그것을 사용하려면'람다 '로 포장해야합니다. – falsetru

+0

@mu 무언가, 당신은 함수를 호출하지 않고 함수를 전달할 수있는 동안 호출하지 않고 연산자를 전달할 수 없습니다. – falsetru