Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Use django query __isnull with field name containing spaces or hyphens

The basic problem is that I can't use the key-value-argument

field_variable_name__isnull=True/False

or

field_variable_name=None

when the field_variable_name contains spaces or hyphens (e.g. 'This is my field variable name', or 'This-is-another-one').

I looked up how to filter a models.object-list with 'varname__isnull=True', but didn't find a solution for the case that a name containing a space-character was given:

In my views.py I have the following function:

def currenttodos(request):
    todos = Todo.objects.filter(user=request.user, time_completed__isnull=True)
    return render(request, 'todo/currenttodos.html', {'todos': todos})

The model Todo in the models.py - file comprises the following field:

time_completed = models.DateTimeField(null=True, blank=True)

This way it works, but actually I wanted to call the time_completed - field differently, for example "Completion time" using the name-parameter:

time_completed = models.DateTimeField(null=True, blank=True, name="Completion time")

Now, the problem is that I can't use the __isnull - parameter since the name contains a space. All of the following examples don't work:

todos = Todo.objects.filter(user=request.user, Completion time__isnull=True)
todos = Todo.objects.filter(user=request.user, "Completion time"__isnull=True)
todos = Todo.objects.filter(user=request.user, "Completion time"=None)
etc.

How can I make this work for names containing spaces or hyphens?

question from:https://stackoverflow.com/questions/65919820/use-django-query-isnull-with-field-name-containing-spaces-or-hyphens

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

1 Answer

0 votes
by (71.8m points)

Here is a link to a similar post: Filtering for empty or NULL names in a queryset

Basically, this user wanted to be able to exclude instances that were null or blank. As you can see there are several options to do this. My preferred approach is to chain together the filter criteria as to me it is more straightforward and easy to understand however you have some options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...