python - 如何通过 tasytpie API 将产品放入购物车?

标签 python django nested tastypie

假设我们有这些模型,原始项目不同,但这是常见的任务:

class Cart(models.Model):
    owner = models.ForeignKey(User)
    products = models.ManyToManyField(Product, symmetrical=False)

class Product(models.Model):
    title = models.CharField(max_length="255")
    description = models.TextField()

现在我想通过 api 将产品放入购物车。

我是这样开始的:

class CartResource(ModelResource):
    products = fields.ManyToManyField(ProductResource, 'products', full=True)

    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/product/(?P<prodcut_id>\w[\w/-]*)/$" % (self._meta.resource_name), self.wrap_view('dispatch_detail_product'), name="api_dispatch_detail_product"),
        ]

    def dispatch_detail_product(.....):
        # A get is not useful or is it?
        # A post could put a product into the cart
        # A put (preferred) could put a product in the cart
        # A delete could delete a product from the cart

    class Meta:
        queryset = Product.objects.all()
        authentication = MyBasicAuthentication()
        authorization = DjangoAuthorization()
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get', 'put', 'delete']

    def obj_update(self, bundle, request=None, **kwargs):
        return super(PrivateSpaceResource, self).obj_create(bundle, request, owner=request.user)

    def apply_authorization_limits(self, request, object_list):
        if len(object_list.filter(owner=request.user)) == 0:
            Cart.objects.create(owner=request.user)
        return object_list.filter(owner=request.user)

但我不确定该怎么做。与 django 相比,tastypie 绝对对开发人员不友好。

最佳答案

我认为您应该创建一个关系资源。请检查下面的代码:

class LikeResource(ModelResource):
    profile = fields.ToOneField(ProfileResource, 'profile',full=True)
    post = fields.ToOneField(PostResource,'post')

    class Meta:
        queryset = Like.objects.all() 
        authentication = ApiKeyAuthentication()
        authorization = DjangoAuthorization()
        resource_name = 'like'
        filtering = {
            'post': 'exact',
            'profile':'exact',
        }

然后您可以向该资源发出 POST 请求以将新产品添加到购物车。

关于python - 如何通过 tasytpie API 将产品放入购物车?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8613522/

相关文章:

python - 更新 ListProperty 时是否可能在 App Engine 出现竞争条件?

python - python 中的 Selenium 和多处理

python - Redis 中哪种抓取方式效率更高?

css - 当文本嵌套在大约 5 个生成的 DIV 标签中时,将文本获取到 "display:inline"的简单方法?

java - 二维映射中的迭代器

javascript - 如何在高空照片中高效地找到地平线?

python - 从大小为 x python 的数组创建形状为 (x**0.5,x**0.5) 的 pandas 框架

Django 表单 "Enter a valid date."

python - Django 对象是 "non subscriptable"导致我编写冗余代码

c++ - 可以为嵌套的私有(private)类重载 operator<< 吗?