1

我可以在哪里放置自定义逻辑或者我应该重载哪个函数来在tastepie中添加自定义逻辑。例如:想要返回CustomObject其中包含name的大写字母,但在返回之前我想将其设为小写。

4

2 回答 2

1

如果您想提供类似的自定义内容,我建议您在dehydrate. 查看文档,该示例几乎就是您要查找的内容:

class MyResource(ModelResource):
    # The ``title`` field is already added to the class by ``ModelResource``
    # and populated off ``Note.title``. But we want allcaps titles...

    class Meta:
        queryset = Note.objects.all()

    def dehydrate_title(self, bundle):
        return bundle.data['title'].upper()

好吧,除了你正在寻找.lower()的当然:)

class CustomObjectResource(ModelResource):

    class Meta:
        queryset = CustomObject.objects.all()

    def dehydrate_title(self, bundle):
        return bundle.data['name'].lower()
于 2013-01-31T14:46:57.587 回答
0

您可以恕我直言覆盖任何字段:

class CustomResource(ModelResource):

    name = fields.CharField(
        attribute='get_lowercased_name', 
        readonly=True 
    )

    class Meta:
        queryset = Custom.objects.all()

你需要在你的模型类上定义get_lowercased_name方法。Custom

于 2013-01-31T12:58:50.473 回答