Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

python - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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_fitler = {
    "customfield_1": "value",
    "customfield_2": "value_2",
    "customfield_3": "value_3"
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...