Search code examples
pythondjangodjango-qdjango-contenttypes

How to generate a combined Q object from a list?


I have a list of dictionaries with app_label and model keys that I got from the ContentType model:

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

I need to generate a set of combined Q objects from this to use as a ForeignKey.limit_choices_to argument. This is the output I need:

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

So I can use it in a model like this:

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')
    # ...

Anyone know how to create a list of combined Q objects with the | operator by looping through this list of dictionaries?


Solution

  • Using reduce with operator.or_ (or lambda a, b: a | b):

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