Ronen Ness
Ronen Ness

Reputation: 10740

django - Q object that don't assert if one or more fields don't exist

Lets say I have the following models:

Model A:
    date
    category
    something
    ...

and:

Model B:
    date
    category
    ...

I want to create a single Q object that will filter by date, category, and something, but only if it exists in the model I apply the filter on.

In other words, a single Q that I can apply on both A and B models, just that with B the something filter will be ignored since this field doesn't exist in B.

If I try a naive implementation, eg a Q with date, category and something in it, when applied on B model I get the following error:

FieldError: Cannot resolve keyword 'something' into field. Choices are...

Which makes sense since B really don't have a field named something in it. But I want to change that behavior and make it work and just ignore the non-existing field instead of throwing an exception.

Is that possible?

Upvotes: 0

Views: 394

Answers (1)

Sherpa
Sherpa

Reputation: 1998

No. However, you can write a function that inspects the model's fields, and generates the appropriate Q object. Something like:

def content_query(model, value):
    allowed = ['date', 'category', 'something']
    model_fields = [f.name for f in model._meta.fields and f.name in allowed]

    return Q(**{f: value for f in model_fields})

Upvotes: 2

Related Questions