Tuesday, June 1, 2010

Raw sql bug? Or am I doing something wrong?

Hi,

I love the new raw() function to write custom sql and get back ORM
objects. However, when using joins, things get weird.

As long as you use "select *", everything works fine:

for r in Model.objects.raw('SELECT * FROM model INNER JOIN othermodel
ON othermodel.model_id = model.id'):
print r

However, this can result in a LOT of columns that you don't need, and
possible duplicate column names.

Solution would seem to be this:

for r in Model.objects.raw('SELECT model.id, model.name FROM model
INNER JOIN othermodel ON othermodel.model_id = model.id'):
print r

Sadly, this doesn't work. I get an "type() argument 1 must be string,
not unicode" error from django/db/models/query_utils.py in
deferred_class_factory, line 274.

Is there another way to get this to work? The "id" column is required
for the raw() function to work, but just using "id" doesn't work
because othermodel also has an "id" column. Using "model.id" gives the
error. I also tried "model.id AS id", but same error.

Or is this a bug that I should put in trac?

Thanks,
Kevin

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment