On Mon, 2009-02-02 at 23:56 -0500, Jack Orenstein wrote:
> Hello, I am new to Django, and trying to figure out how best to use  
> it. My immediate problem is that I'm trying to figure out how to use  
> raw SQL in combination with the model layer. Here are the issues I've  
> run into:
> 
> 1) How do I turn a row into a model object? There is some discussion  
> of writing raw SQL in the docs (http://docs.djangoproject.com/en/dev/ 
> topics/db/sql/#topics-db-sql), but I didn't see anything on turning  
> the row into a model object. Do I need to create a dict from the row  
> values and then call the model object's __init__ method?

Yes.

>  Or is there  
> something simpler that I'm missing?

I realise that's just a turn of phrase, but when I read it literally, I
have to wonder just how much simpler could it get? :-)

You know the field attribute names, since you constructed the query.You
have their values, returned from the database. So it's a one-liner:

        MyModel(**dict(zip(field_names, row_data)))


> 2) If the model object as a ForeignKey, then the construction of a  
> model object is trickier. From playing around, it appears to be the  
> case that the dict must have an object of the referenced type, not  
> the value of the foreign key. This could make manual construction of  
> model objects difficult. I must be doing something wrong -- forcing  
> creation of the related objects seems wasteful, especially as it  
> could propagate, (if the referenced object has its own FKs).

If you know the id value for the referenced model, you can assign to the
'*_id' attribute, which is the hidden field containing the related value
(not the referred-to instance). For example, with a ForeignKey field
called "foo", you can create a model with foo_id=6 or whatever, to set
the appropriate element.

Regards,
malcolm


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

Reply via email to