Create function in database using django ORM - django

In my project I want to get people who have birthday between some days, I hope to find a solution which does not force any limitations to queries.
I have found this solution which seems efficient and suite for my problem. But now I have a second problem to create the function in database using django ORM, because this must be portable and works with test database also. I could not find any proper way to able to define the function and the index based on it in django.
In brief I want to create below function in database using django:
CREATE OR REPLACE FUNCTION indexable_month_day(date) RETURNS TEXT as $BODY$
SELECT to_char($1, 'MM-DD');
$BODY$ language 'sql' IMMUTABLE STRICT;
CREATE INDEX person_birthday_idx ON people (indexable_month_day(dob));

To answer your question, using RunSQL you can insert raw SQL into a migration
-- it looks like you should be able to put this raw SQL into a migration file, including the function that would create the custom index. So running the migration would create the custom in
But don't do this -- you should just use Django to index the dob field, i.e.
dob = models.DateField(db_index=True)
and use Django to write your queries as well.

Related

Django: how do i create a model dynamically

How do I create a model dynamically upon uploading a csv file? I have done the part where it can read the csv file.
This doc explains very well how to dynamically create models at runtime in django. It also links to an example of doing so.
However, as you will see after looking at the document, it is quite complex and cumbersome to do this. I would not recommend doing this and believe it is quite likely you can determine a model ahead of time that is flexible enough to handle the CSV. This would be much better practice since dynamically changing the schema of your database as your application is running is a recipe for a ton of bugs in your code.
I understand that you want to create new schema's on the fly based on fields in the those in a CSV. While thats a valid use case and could be the absolute right call. I doubt it though - it lends itself to a data model for a single tenet SaaS application that could have goofy performance and migration issues.
I'd try using Mongo/ some other NoSQL solutions as others have mentioned. But a simpler approach may be a modified Star Schema implemented in SQL. In this case you create a dimensions tables that stores each header, then create an instance of each data element that has a foreign key to dimension and records the value of that dimension.
If you read the csv the psuedo code would look something like this:
for row in DictReader(file):
for k in row.keys():
try:
dim = Dimension.objects.get(name=k)
except:
dim = Dimension(name=k)
dim.save()
DimensionRecord(dimension=dim, value=row[k]
Obviously you could better handle reading the headers and error trapping if dimensions already exist, but this would be an example of how you could dynamically load variable headered CSV's into a SQL db.

Postgres select function in Django annotation

I have old database and need custom select.
in sql i can use:
SELECT x(geometry) FROM table
but I dont know how to force x() function in django select.
You can create a custom function using Expressions.
class GeoX(Func):
function = 'X'
MyModel.objects.annotate(x=GeoX('field'))
This will result in the geometry X function being invoked and it's result being annotated to a field labeled x in your model. However this is the inferior solution. The better solution is to install geodjango. That provides full access to almost every single function in PostGIS. Also works with spatialite and msyql spatial extensions.
I managed to solve problem using Func()
Func(F('geometry'), function='x')

syncdb-like tool for Kohana

I've used Django(python) previously and now I'm learning Kohana (PHP). It seems to be good, but I wonder if there is something like "django-admin.py syncdb" in Kohana, or at least, a tool that makes the same job.
Django Model knows all information about their field before start working with database. Kohana Models, in contrast, knows only table name and on first using ORM authomaticaly calls ORM::list_columns() which executing sql query
SHOW FULL COLUMNS FROM `tablename`
and fill protected $_table_columns variable for this Model

Django: Possible to load fixtures with date fields based on the current date?

I want to load fixtures into django. The data has some date fields - is it possible to create these data so they will always be e.g. yesterday or tomorrow? I want to make sure certain data is always fresh, but also so I can easily test edge cases (e.g. whether an object is enabled if the publishing date is today, etc).
Fixtures just load text data files (in JSON/XML/YAML) so, there's no real way to insert dynamically generated data by just loading a fixture. On the other hand, you can get around this using other methods.
One option is the package django-fixture-generator where you can write python/django code to create data and it will be inserted before your tests are called.
Another option is a previous SO question: How to load sql fixture in Django for User model?. This has some code on using SQL files for fixtures, where you can use a SQL expression for your date requirements (e.g. GETDATE()+1 or similar in your SQL dialect).

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!
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.