【问题标题】:Let tastypie client do CRUD without foreign key lookups让 sweetpie 客户端在没有外键查找的情况下进行 CRUD
【发布时间】:2013-04-29 22:27:02
【问题描述】:

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

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 类,该类将使用它自己的 hydrate 和 dehydrate 来做到这一点,但这让我觉得我可能遗漏了一些东西。我怎样才能让客户这样做,例如:

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

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    您可以添加一个新的 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
    

    【讨论】:

    • 这似乎无法处理过滤。
    猜你喜欢
    • 2018-05-03
    • 2013-02-12
    • 1970-01-01
    • 2011-01-04
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多