Python 如何通过tasytpie API将产品放入购物车?
假设我们有这些模型,原始项目不同,但这是常见的任务:Python 如何通过tasytpie API将产品放入购物车?,python,django,nested,tastypie,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 =
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)
类资源(ModelResource):
products=字段.ManyToManyField(ProductResource,'products',full=True)
def覆盖URL(自身):
返回[
url(r“^(?P%s)/product/(?P\w[\w/-]*)/$”%(self.\u meta.resource\u name)、self.wrap\u视图('dispatch\u detail\u product')、name=“api\u dispatch\u detail\u product”),
]
def调度_详情_产品(…):
#get是没有用的,是吗?
#邮件可以将产品放入购物车
#put(首选)可以将产品放入购物车
#删除可以从购物车中删除产品
类元:
queryset=Product.objects.all()
身份验证=MyBasicAuthentication()
authorization=DjangoAuthorization()
列出\u允许的\u方法=['get']
允许的详细信息\u方法=['get','put','delete']
def obj_更新(自我、捆绑、请求=无,**kwargs):
返回super(privatespaceesource,self).obj_创建(bundle,request,owner=request.user)
def应用授权限制(自身、请求、对象列表):
如果len(object_list.filter(owner=request.user))=0:
Cart.objects.create(owner=request.user)
返回对象\u list.filter(所有者=请求.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请求,向购物车添加新产品。我将此问题标记为已解决,但我没有测试它!没有使用tastypie。