On Feb 3, 2009, at 12:15 AM, Malcolm Tredinnick wrote:

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

This is pretty simple, I agree. I came up with this exact code, but  
then ran into the FK problem, at which point I started wondering if I  
was just going about things the wrong way.

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

Excellent, thanks.

Jack

--~--~---------~--~----~------------~-------~--~----~
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+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to