Tastypie ordering of nested relationships

2019-06-14 14:24发布

问题:

I am using a nested relationship to return grouped messages and was wondering how i can order the nested messages so that they are ordered chronologically.

class MessageGroupResource(ModelResource):
  messages = fields.ToManyField('lookup.api.MessageResource', 'message_set', full=True);
  class Meta:
    queryset = MessageGroup.objects.all();
    resource_name = 'message'
    authorization= UserAuthorization()
    ordering  = [
                 'sendTime',                    
                ]



class MessageResource(ModelResource):
  messageGroup = fields.ForeignKey(MessageGroupResource, 'messageGroup')
  class Meta:
    queryset = Message.objects.all()
    resource_name = 'submessage'
    authorization= UserAuthorization()

回答1:

This is one way to do it; however, I don't know if there's a better/more API standard way of doing this.

class MessageGroupResource(ModelResource):

messages = fields.ToManyField(MessageResource,
    attribute=lambda bundle: bundle.obj.MessageResource.all().order_by("sendTime"))


标签: tastypie