让Tastype客户端在没有外键查找的情况下执行CRUD

2024-09-30 20:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用TastyPie创建一个REST客户机/服务器,用于访问有关系统级构建后测试的一些数据。我希望客户机能够忽略product作为外键在内部存储的事实,并使用产品和标记名执行CRUD操作。本质上,我希望客户机脚本以CharFields的形式与“product”和“tag”交互,但将这些信息作为外键保存在服务器上。这是我的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类,它可以使用它自己的水合物和脱水剂来完成这项工作,但这让我觉得我可能遗漏了一些东西。我如何允许客户做,例如:

^{pr2}$

Tags: namefromimporttruefields客户机objectsall
1条回答
网友
1楼 · 发布于 2024-09-30 20:22:49

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

相关问题 更多 >