How to put Product to Cart via tasytpie API?

半城伤御伤魂 提交于 2019-12-01 05:41:53

问题


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()

Now I want to put a Product into the Cart via the api.

I started like this:

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)

But I'm not sure what to do. Compared to django, tastypie is absolute developer-unfriendly.


回答1:


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',
        }

Then you can make POST request to that resource to add a new Product to the Cart.



来源:https://stackoverflow.com/questions/8613522/how-to-put-product-to-cart-via-tasytpie-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!