How to add result of a custom filter query serialized as json

350 views
Skip to first unread message

jjclockwise

unread,
May 27, 2012, 6:30:21 AM5/27/12
to Tastypie
Hi, I am new to django and tastypie. I am trying to add a list of
model objects returned from a query to my resource.

I have the following model in django:

class League(models.Model):
name = models.CharField(max_length=100, verbose_name=u'Ligin Adı')
start_date = models.DateField(verbose_name=u'Ligin başlama
tarihi')
end_date = models.DateField(verbose_name=u'Ligin bitiş tarihi')

class LeagueRegistration(models.Model):
team = models.ForeignKey(Team)
league = models.ForeignKey(League)

I defined the following resource:

class LeagueResource(ModelResource):
class Meta:
queryset = League.objects.all()
resource_name = 'league'
def dehydrate(self, bundle):
bundle.data['registrations'] =
LeagueRegistration.objects.filter(league=bundle.obj.pk)
return bundle

I want to return the league with its registrations. The query is
working fine but the value of registration fiels is not serialized
into json:

"registrations":
"[<LeagueRegistration>,<LeagueRegistration>,<LeagueRegistration>]"

How can I make this list to be serialized into json before returning?

Josh Bohde

unread,
May 27, 2012, 8:05:23 AM5/27/12
to django-...@googlegroups.com
The easiest way is to use the builting ToMany field: http://readthedocs.org/docs/django-tastypie/en/latest/fields.html#tomanyfield

An example implementation is here:  https://gist.github.com/2811271

- Josh

kahara

unread,
May 27, 2012, 8:17:54 AM5/27/12
to Tastypie
Howdy.

Would this be more natural if the League model had a "teams"
ManyToManyField, and the LeagueResource a corresponding (Tastypie)
field?


/j

jjclockwise

unread,
May 27, 2012, 10:32:05 AM5/27/12
to Tastypie
Hi Josh,

I have tried using ToMany field before but couldn't make it work. I
gave it another try anyway and I got this error "'League' object has
no attribute 'leagueregistrations_set'". So I guess I need to have a
leagueregistrations_set attribute on my League model which I don't
have.

On May 27, 3:05 pm, Josh Bohde <josh.bo...@gmail.com> wrote:
> The easiest way is to use the builting ToMany field:http://readthedocs.org/docs/django-tastypie/en/latest/fields.html#tom...
>
> An example implementation is here:  https://gist.github.com/2811271
>
> - Josh
>

jjclockwise

unread,
May 27, 2012, 10:35:23 AM5/27/12
to Tastypie
Hi kahara,

League model doesn't have reference to teams or registrations. Each
registration has a reference to Team and User. I didn't want to add
reference to LeagueRegistration model on League model because it
didn't seem necessary. Maybe the source of my problem is that I didnt
model everything right. I wanted to be sure if I am not using tastypie
right or if my model is wrong.
Reply all
Reply to author
Forward
0 new messages