On Wed, 2009-03-25 at 20:38 -0700, adrian wrote:
> 
> I have a Sighting model which has a foreign key field "notes" to a
> model called Notes.
> Notes has a predefined empty note with id=1.   If the user specifies
> no note then
> I want the sighting to reference this predefined empty note.
> So in my view:
> 
> note = form.cleaned_data['notes']
> if note != "":  # notes field not blank, save note to db
>                 notes_object = Notes(notes=note)
>                 notes_object.save()
>     else:  #get blank note instance
>                 notes_queryset = Notes.objects.get(
>                     id__exact=1
>                 )
>                 notes_object = notes_queryset[0]
> 
> sighting = Sighting(
>                 #more fields here
>                 notes = notes_object,
>                 #more fields
>             )
> 
> I have two questions about this.
> 
> First, sometimes I'm getting an error:
> TypeError: 'Notes' object is unindexable   (on the line with
> notes_queryset[0] )
> Am I doing this right?  The Notes with id=1 is definitely present in
> the database.
> I thought a queryset always returned a list of model instance objects
> (in this case a list of 1).

There are a bunch of queryset methods that do not return a queryset.
They return something else. The get() method is one of those: it returns
an object. So, in fact, *every* time you hit that line you will see the
error, since Notes.objects.get(id=1) returns a Note object, not a
queryset.

The methods for querysets are divided into two sections in the
documentation, along those lines (returns a queryset or doesn't). get()
leads off this section:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#queryset-methods-that-do-not-return-querysets

> Second, when the note is empty, is there a way to avoid querying the
> database to create the instance of Notes?  Since I already know the id
> and all the contents, the query gives no new information.   Just
> curious, not a big performance hit!

For each foreign key attribute, there is a hidden attribute that stores
the actual data value (as opposed to the reference to the other model).
Normally, it will have the same name as the attribute with "_id"
appended. So you can assign the pk value of the default Note to that:

        sighting = Sighting(..., notes_id=1, ....)
        
... assuming your default version has pk of "1" -- adjust to taste.

This is slightly internal API, so I don't think it's documented
anywhere. But it works.

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