如果存在,如何禁用创建资源?

时间:2012-11-13 14:53:32

标签: django tastypie

我可以使用post方法创建MessageResource,但是,如果MessageResource文本已经存在于数据库中,我想返回类似“message exists”的内容。怎么实现呢?我的MessageResource

class MessageResource(ModelResource):
    class Meta:
        queryset = Message.objects.all()
        resource_name = "message"
        always_return_data = True
        authentication = Authentication()
        authorization = Authorization()

        filtering = {
                'body': ALL
                }

    def determine_format(self, request):
        return "application/json"

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

from tastypie.exceptions import BadRequest

class MessageResource(ModelResource):
    class Meta:
        queryset = Message.objects.all()
        resource_name = "message"
        always_return_data = True
        authentication = Authentication()
        authorization = Authorization()

        filtering = {
            'body': ALL
            }

    def determine_format(self, request):
        return "application/json"

    def hydrate(self, bundle):
        if not bundle.obj.pk and len(Message.objects.filter(text=bundle.obj.text)) > 0:
            raise BadRequest('Message exists')
        return bundle   

或者您也可以使用validation