Re: Serialize with foreign key

2007-06-01 Thread Russell Keith-Magee

On 6/2/07, emailgregn <[EMAIL PROTECTED]> wrote:
>
> Hi everyone,
>
> How can I get foreign key fields serialized ?

The problem you have is not to serialize the keys, but to find the
dependencies that need to be serialized. Although the serializer _can_
take a queryset, it only does so as a degenerate case of a list of
objects. You can pass _any_ list of _any_ objects into the serializer,
and it will spit them out as serialized data. So:

jstr = serializers.serialize('json', list(Book.objects.all()) +
list(Author.objects.all()))

will serialize all the books and authors.

However, if you only want the authors related to a subset of books,
you will need to do some filtering. There isn't currently a built-in
method for determining dependencies, so you'll need to work out the
dependency list yourself.

In your specfic case, you can filter fairly easily by getting all the
books, then getting all the authors from those books. The generic case
is a little harder, but shouldn't be too difficult. If you (or anyone
else for that matter) wanted to contribute a generic dependency
generating algorithm, I'd be happy to commit it to trunk.

Yours,
Russ Magee %-)

--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Serialize with foreign key

2007-06-01 Thread emailgregn

Hi everyone,

How can I get foreign key fields serialized ?
I can't get the desired effect with:
select_related() or
Book.objects.extra(select={'firstname': 'subselect for firstname',
'lastname',' subselect for lastname' })
but don't want to iterate over the whole queryset unnecessarily.

Model
class Author( models.Model):
   firstname = models.CharField(maxlength=255)
   lastname = models.CharField(maxlength=255)

class Book( model.Model):
title = model.CharField(maxlength=255)
author = models.ForeignKey(Author)

mylist = Book.objects.all()
jstr = serializers.serialize('json', mylist )

The author_id will be in jstr but I want to get firstname and lastname
in there too.

Many Thanks,
Greg


--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---