Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django query based on dynamic property()

I was wondering if there was a way to use Django's filter() on query sets using a dynamically generated python property using property(). I have first_name and last_name of every user, and I want to filter based on their concatenated name first_name last_name. (The reason behind this is that when I do autocomplete I search to see if the query matches first name, last name, or part of the concatenation. I want John S to match John Smith, for example.

I created a property of name:

def _get_name(self):
    return self.first_name + " " + self.last_name
    name = property(_get_name)

This way I can call user.name to get the concatenated name.

However, if I try to do User.objects.filter(name__istartswith=query) I get the error Cannot resolve keyword 'name' into field.

Any ideas on how to do this? Do I have to create another field in the database to store the full name?

like image 507
munchybunch Avatar asked Jan 21 '11 00:01

munchybunch


People also ask

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What does .values do in Django?

The values_list() method allows you to return only the columns that you specify.

How to save to a model in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.


1 Answers

filter() operates on the database level (it actually writes SQL), so it won't be possible to use it for any queries based on your python code (dynamic property in your question).

This is an answer put together from many other answers in this department : )

like image 166
Yuji 'Tomita' Tomita Avatar answered Sep 27 '22 19:09

Yuji 'Tomita' Tomita