2013-04-29 72 views
1

我使用TastyPie来创建REST客户端/服务器以访问有关我们的系统级构建后测试的一些数据。我希望客户能够忽略产品在内部存储为外键的事实,并使用产品和标签名称执行CRUD操作。实质上,我希望客户端脚本与CharFields的“产品”和“标签”进行交互,但要将此信息作为外键保存在服务器上。这里是我的api.py:让tastypie客户端在没有外键查询的情况下执行CRUD

from tastypie import fields 
from tastypie.resources import ModelResource 
from models import Test, Product, Tag 

class ProductResource(ModelResource): 
    name = fields.CharField('name', unique=True) 
    class Meta: 
     queryset = Product.objects.all() 
     filtering = {'iexact', 'exact'} 

class TagResource(ModelResource): 
    name = fields.CharField('name', unique=True) 
    class Meta: 
     queryset = Tag.objects.all() 
     filtering = {'iexact', 'exact'} 

class TestResource(ModelResource): 
    product = fields.ForeignKey(ProductResource, 'product', full=True) 
    tags = fields.ForeignKey(TagResource, 'tags', full=True) 
    command = fields.CharField('command') 
    class Meta: 
     queryset = Test.objects.all() 
     filtering = {'product': tastypie.constants.ALL_WITH_RELATIONS, 
        'tag': tastypie.constants.ALL_WITH_RELATIONS} 

我目前工作的一个自定义的ApiField类,将做到这一点使用自己的水合物和脱水,但是这让我觉得我可能失去了一些东西。我怎样才能让客户端做的,例如:

curl -H "Content-Type: application/json" -X POST --data '{"product": "fisherman", "command": "go fish"}' /api/v1/test/ 

回答

0

您可以在前面加上一个新的URL来处理你的命令:

class TestResource(ModelResource): 
    ... 
    def prepend_urls(self): 
     return [ 
     url(r"^(?P<resource_name>%s)/commands$" % self._meta.resource_name, self.wrap_view('handle_commands'), name="api_handle_commands"), 
    ] 


def handle_commands(self, request): 
    command = request.POST['command'] 
    product = Product.objects.get(name=request.POST['product']) 
    # do your stuff 
+0

这似乎并没有处理过滤。 – dbn 2013-05-13 21:18:56

相关问题