Khakis7
Khakis7

Reputation: 433

Django Filter queryset if property exists

I'm attempting to filter out objects that don't have a custom field existing on them.

For example:

the returned list might have the following properties

customfield_1: value
customfield_2: value_2
customfield_3: value_3

In the returned list not all objects might have the property customfield_3, so I'd like to filter those values out.

Doing something like

queryset.exlude(customfield_3=None) 

does not work because it isn't that the property has a value of null, but that the property does not exist on the object at all.

The resulting list is built from a table that maps together service items via a link.

Service
Service Type,
ect.

Link
Parent_Service_Id
Child_Service_Id

This lets me build out a list that acts as a tree. The field I'm attempting to exclude on is when service type is set to a custom value. Normal values are things such as epics, stories, ect. (this comes from Jira), but Jira can also include custom fields.

So, is it possible to add a filter to the queryset that checks if the object has the existence of a property?

Upvotes: 1

Views: 1416

Answers (1)

NKSM
NKSM

Reputation: 5854

First of all, you can check if the model has this field:

queryset.model._meta.get_field(field)

Then you can do something like that:

from django.db import models

query_filter = {
    "customfield_1": "value",
    "customfield_2": "value_2",
    "customfield_3": "value_3"
}

for field in query_filter:
    try:
        queryset.model._meta.get_field(field)
    except models.FieldDoesNotExist:
        # remove field 
        query_filter.pop(field, None)

# then filter the queryset
queryset.exclude(**query_filter)

Upvotes: 1

Related Questions