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?
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.
The values_list() method allows you to return only the columns that you specify.
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.
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 : )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With