从 tastypie 中排除一个字段 api

Exclude a field from tastypie api

我需要根据其他字段的值排除一个字段。它们之间的关系如下

class Moo: 
   ...

class Too:
        moo = models.ForeignKey(Moo, related_name='moo_too')

        ...

class PooToo:
       moo = models.ForeignKey(Moo) 
       stature = models.PositiveSmallIntegerField(..)
       ...

class PooMooResource(ModelResource):

    moo = ToOneField(StandAloneMooResource, 'moo', full=True)
    class Meta:
        list_allowed_methods = ['get']
        queryset = PooMoo.objects.select_related('moo').all()

class StandAloneMooResource(ModelResource):

    too = ToManyField(TooResource,...)
    class Meta:
            queryset = Moo.objects.all()

现在我只想在 stature==0 时公开 API 中的 too 字段,否则不公开。我可以为此使用 use_in,但问题是我在 StandAloneMooResource

中没有 stature 的值

您可以执行以下操作:

class StandAloneMooResource(ModelResource):

    tutorials = ToManyField(TutorialResource,...)
    class Meta:
        queryset = Moo.objects.filter(Q(pootoo__isnull = False, pootoo__status=0) | Q(pootoo__isnull=True))

你可以查看http://django-tastypie.readthedocs.org/en/latest/resources.html

尝试这样的事情:

class StandAloneMooResource(ModelResource):

    too = ToManyField(TooResource,...)
    class Meta:
        queryset = Moo.objects.all()

    def dehydrate_too(self, bundle):
        # if this method is run while dehdyrating PooMooResource.moo,
        # related_obj should be the related PooMoo
        if bundle.related_obj and bundle.related_obj.stature != 0:
            return None
        return bundle.data['too']

不幸的是,'too' 密钥仍然存在,tastypie 仍将努力从数据库中检索教程。

这可能会更好:

def foo(bundle):
    if bundle.related_obj and bundle.related_obj.stature != 0:
        return None
    return bundle.obj.tutorials.all()

class StandAloneMooResource(ModelResource):

    too = ToManyField(TooResource, attribute=foo)
    class Meta:
        queryset = Moo.objects.all()

    def dehydrate(self, bundle):
        # to remove the 'tutorials' key
        if 'too' in bundle.data and not bundle.data['too']:
            del bundle.data['too']
        return bundle

如果 bundle.related_obj 不工作:

def foo(bundle):
    poomoo = None
    try:
        # assumes PooMoo.user a relation to User
        poomoo = PooMoo.objects.filter(moo=bundle.obj, user=bundle.request.user)[0]
    except IndexError:
        pass
    if poomoo and poomoo.stature != 0:
        return None
    return bundle.obj.too.all()