开发者

Proper way to call a database function from Django?

开发者 https://www.devze.com 2023-01-11 12:00 出处:网络
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:

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 * FR开发者_JS百科OM 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!


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')")


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


First, you probably don't want to do this. Do you have proof that your database function is actually faster?

Implement this in Python first. When you can prove that your Python implementation really is the slowest part of your transaction, then you can try a stored procedure.

Second, you have the extra method available in Django.

http://docs.djangoproject.com/en/1.2/ref/models/querysets/#django.db.models.QuerySet.extra

Note that compute-intensive database procedures are often slow.

0

精彩评论

暂无评论...
验证码 换一张
取 消