2013-12-20 24 views
1

我有兩個型號產品和CartItem:Django的TastyPie ForeignKey的完整=真不工作

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

我想所有cartitems的車,對於在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,它沒有產品名稱或描述。我也想在響應中獲得產品名稱。從我讀完全=真的是最好的解決方案(最低要求,因爲購物車可以有多個購物車項目)。

回答

1

您的get_cart_items()版本未使用Tastypie代碼進行讀取,這就是爲什麼full = True不起作用的原因。

full=True將工作,如果您使用Tastypie默認處理程序來獲取數據。你不需要編寫你自己的get_cart_items()。

+0

感謝您的回覆。我應該使用'def obj_get_list(self,bundle,** kwargs):cart_id = request.GET.get('cart_id')...' – reevh

+0

我不完全理解你想要做什麼,但是在一般情況下你根本不需要編寫任何代碼,只需使用默認的tastypie url。 – dragonx

+0

我想將/ api/cart_item/cart /?id = 1這樣的網址反對/ api/cart_item/cart /?cart__id = id。我會嘗試與後者,如果它的作品將接受你的答案。謝謝你的幫助。我是新來的django-tastypie :) – reevh