【问题标题】:Django TastyPie ForeignKey full = true not workingDjango TastyPie ForeignKey full = true 不工作
【发布时间】:2013-12-20 17:17:10
【问题描述】:

我有两个模型 Product 和 CartItem :

#product models.py
class Product(models.Model):
   objects = ProductManger()
   name = models.CharField(max_length=200)
   brand_name = models.CharField(max_length=100)
   description = models.TextField()

#CartItem models.py
class CartItem(models.Model):
   objects = CartItemManager()
   cart = models.ForeignKey(Cart)
   product = models.ForeignKey(Product)
   quantity = models.PositiveSmallIntegerField(blank=True, null=True, default=1)

我想获取购物车的所有购物车,对于 api.py (tastypie) 我有以下内容:

class CartItemRelatedResource(ModelResource):

    class Meta:
       queryset = Product.objects.all()
       resource_name = 'item_product'
       allowed_methods = ['get'] 
       include_resource_uri = False       
       authentication = SessionAuthentication()

class CartItemResource(ModelResource):
     product = fields.ForeignKey(CartItemRelatedResource, 'product', full=True)

    class Meta:
       queryset = CartItem.objects.all()
       resource_name = 'cart_item'
       excludes = ['modification_date']
       allowed_methods = ['post', 'get', 'delete']
       authentication = SessionAuthentication()

    def get_cart_items(self, request, **kwargs):
       self.method_check(request, allowed=['get'])
       self.is_authenticated(request)
       cart_id = request.GET.get('id', '')
       items = CartItem.objects.filter(cart__exact = cart_id)
       data = serializers.serialize('json', items)
       return HttpResponse(data, mimetype='application/json')

但是当我get_cart_items,响应有产品的pk,它没有产品名称或描述。我也想在响应中获取产品名称。根据我的阅读,full=true 是最好的解决方案(请求最少,因为一个购物车可以有多个购物车项目)。

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    您的 get_cart_items() 版本没有使用 Tastypie 代码来获取,这就是 full=True 不起作用的原因。

    full=True 将在您使用 Tastypie 默认处理程序获取数据时起作用。您不需要编写自己的 get_cart_items()。

    【讨论】:

    • 感谢您的回复。我应该使用def obj_get_list(self, bundle, **kwargs): cart_id= request.GET.get('cart_id') ...
    • 我不完全明白你要做什么,但一般情况下你根本不需要写任何代码,只需使用默认的美味 url。
    • 我希望 /api/cart_item/cart/?id=1 之类的 url 与 /api/cart_item/cart/?cart__id=id 相对。我将尝试后一个,如果它有效,将接受您的回答。谢谢你的帮助。我是 django-tastypie 的新手 :)
    • 哦,我明白了。如果您在答案中添加它会有所帮助。最好覆盖 check_filters() 和 build_filters() 函数以允许您的过滤器。
    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 2012-03-15
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2016-02-16
    • 2012-01-28
    相关资源
    最近更新 更多