Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to call a database function from Django?

i'm triyng to make a full text search with postgresql and django So I've created a function search_client(text) which returns a list of clients. To call it from the DB i use something like this:

SELECT * FROM search_client('something')

and i'm not really sure how to call it from django. i know i could do something like

cursor = connection.cursor()
cursor.execute("SELECT * FROM search_client('something')")
result = cursor.fetchall()

but that will only return a list of values, and i'd like to have a list of objects, like when i use the "filter()" method.

Any ideas?? thanks for your time!

like image 803
pleasedontbelong Avatar asked Aug 12 '10 12:08

pleasedontbelong


2 Answers

If your goal is a full-featured search engine, have a look at django-haystack. It rocks.

As for your question, the new (Django 1.2) raw method might work:

qs = MyModel.objects.raw("SELECT * FROM search_client('something')")
like image 76
Benjamin Wohlwend Avatar answered Oct 14 '22 00:10

Benjamin Wohlwend


If you're using Django 1.2, you can use the raw() ORM method to execute custom SQL but get back Django models. If you're not, you can still execute the SQL via the extra() method on default QuerySet, and pump it into a custom method to either then go pull the real ORM records, or make new, temporary, objects

like image 40
Steve Jalim Avatar answered Oct 13 '22 22:10

Steve Jalim