How to put Product to Cart via tasytpie API?(如何通过 tasytpie API 将产品放入购物车?)
问题描述
假设我们有这些模型,原始项目不同,但这将是常见任务:
Let's assume we have these models, original project differs but this would be the common task:
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 将产品放入购物车.
Now I want to put a Product into the Cart via the 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 绝对对开发人员不友好.
But I'm not sure what to do. Compared to django, tastypie is absolute developer-unfriendly.
推荐答案
我认为您应该创建一个关系资源.请检查以下代码:
I think you should create a relationship resource. Pls check the code below:
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 请求以将新产品添加到购物车.
Then you can make POST request to that resource to add a new Product to the Cart.
这篇关于如何通过 tasytpie API 将产品放入购物车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过 tasytpie API 将产品放入购物车?
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01