tastypie过滤外键相关资源

时间:2013-01-03 02:24:29

标签: python django foreign-key-relationship tastypie

我有一个问题,无论如何我真的无法解决。

我想要的是,从api / epg获取他们的节目在现在和2小时后的范围内的频道。不知怎的,我得到了所有节目的所有频道,而不是时间范围内的任何频道。

我做错了什么?

谢谢

models.py

class Channels(models.Model):
    sort_order = models.IntegerField()
    name = models.CharField(max_length=200)

    def __unicode__(self):
        return self.name


class Events(models.Model):

    event_id = models.CharField(max_length=200, primary_key=True)
    channel = models.ForeignKey('Channels', related_name='events')
    start_time = models.DateTimeField( blank=True, null = True)
    end_time = models.DateTimeField( blank=True, null = True)

    def __unicode__(self):
        return self.title

api.py

class EPGResource(ModelResource):
    events= fields.ToManyField('xyz.api.EventResource','events',  full=True)

    class Meta:
        now = datetime.now()
        later = now + timedelta(hours=2)
        queryset = Channels.objects.filter(events__start_time__range(now,later)).order_by('sort_order')
        resource_name = 'epg'
        filtering = {
          "start_time"  :   ['exact', 'range'],
          "name"  :   ['exact', 'range'],
          "events"  :   ['exact', 'range'],
          "channels": ALL_WITH_RELATIONS,
        }



class EventResource(ModelResource):

    class Meta:
        queryset = Events.objects.all()
        resource_name = 'events'

        filtering = {
          "start_time"  :   ['exact', 'range'],
          "genre"  :   ['exact', 'range'],
          "channel": ALL_WITH_RELATIONS,
        }

1 个答案:

答案 0 :(得分:0)

不幸的是,由于tastypie资源不是在运行时构建的,因此您需要在get_object_list中执行此过滤:

class EPGResource(ModelResource):
    events= fields.ToManyField('xyz.api.EventResource','events',  full=True)

    class Meta:
        now = datetime.now()
        later = now + timedelta(hours=2)
        queryset = Channels.objects.all()
        resource_name = 'epg'
        filtering = {
          "start_time"  :   ['exact', 'range'],
          "name"  :   ['exact', 'range'],
          "events"  :   ['exact', 'range'],
          "channels": ALL_WITH_RELATIONS,
        }

    def get_object_list(self, request):
        now = datetime.now()
        later = now + timedelta(hours=2)
        return super(EPGResource, self).get_object_list(request).filter(events__start_time__range(now,later)).order_by('sort_order')