Ace_Gentile Ace_Gentile - 14 days ago 6
Python Question

Django: declare key aliases into objects.filter function

I have a labelling problem that should be pretty easy but strangely I cannot find a way out to do that.

I have this filtering function

def search(cls, query):
return cls.objects.filter(label__icontains=query)


And my model is just made up by a key and a label field. What I obtain looks like this

[{"id": 20, "label": "Title 1"}, {"id": 22, "label": "Title 2"}]


But I want just in my output use "name" instead of "label" and "key" instead of "id" alias, like this:

[{"key": 20, "name": "Title 1"}, {"key": 22, "name": "Title 2"}]


How can I declare these aliases directly into my filtering function without coding that elsewhere?

Answer

You can make use of django's F expressions.

def search(cls, query):
    qs = cls.objects.filter(label__icontains=query)
    return qs.annotate(key=F('id'), name=F('label')).values('key', 'name')

That way django will basically generate a query SELECT id as key, label as name FROM ....

Comments