如何获取查询集中的外键字段的字段

时间:2014-04-07 03:51:24

标签: python django

我有以下型号:

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

 class Cart(models.Model):
    user = models.ForeignKey(User)
    creation_date = models.DateTimeField(auto_now_add=True)
    modification_date = models.DateTimeField(auto_now=True, auto_now_add=True)
    is_check_out = models.BooleanField(default=False)

 class CartItem(models.Model):
    objects = CartItemManager()
    cart = models.ForeignKey(Cart)
    product = models.ForeignKey(Product)
    quantity = models.PositiveSmallIntegerField(default=1)

我想在购物车中获得所有cartItems 的 JSON(其中is_check_out = False),为此我有以下代码:

  def get_user_cart(self, request, **kwargs):
    self.method_check(request, allowed=['get'])
    self.is_authenticated(request)

    cart, created = Cart.objects.get_or_create(user__exact=request.user, is_check_out=False)

    if not created:
        items = CartItem.objects.filter(cart=cart)

        d = []
        for item in items:
            print item.product
            d.append(model_to_dict(item))
        data = [ { 'cart_id':cart.id, 'items':d} ]
    else:
        data = [ { 'cart_id':cart.id, 'items':[]} ]
    data_string = json.dumps(data, cls=DjangoJSONEncoder)
    return HttpResponse(data_string, mimetype='application/json')

这给了我以下JSON:

 [
      {
        "items": [
            {
                "product": 48,
                "price": "0.69",
                "tax": "0.09",
                "cart": 169,
                "note": null,
                "id": 467,
                "quantity": 1
            }
         ],
        "cart_id": 169
     }
    ]

但我正在寻找的是:

[
    {
        "items": [
            {
                "product": {
                    "id": 1,
                    "name": "apple",
                    "image_url": "http://localhost"
                },
                "price": "0.69",
                "tax": "0.09",
                "cart": 169,
                "note": null,
                "id": 467,
                "quantity": 1
            }
        ],
        "cart_id": 169
    }
]

更新 我将get_user_cart更改为以下内容以实现我的目标;如果有更好的方法,请评论或回答。

def get_user_cart(self, request, **kwargs):
    self.method_check(request, allowed=['get'])
    self.is_authenticated(request)       
    cart, created = Cart.objects.get_or_create(user__exact=request.user, is_check_out=False)        
    if not created:
        items = CartItem.objects.select_related('product').filter(cart=cart)
        d = []            
        for item in items:
            d.append({
                      "product": {
                            "id": item.product.id,
                            "name": item.product.name,
                            "image_url": item.product.image_url
                        }, 
                      'price': item.price,
                      'tax': item.tax,
                      'cart':item.cart.id,
                      'note': item.note,
                      'id':item.id,
                      'quantity':item.quantity                          
                      })
        data = [ { 'cart_id':cart.id, 'items':d} ]
    else:
        data = [ { 'cart_id':cart.id, 'items':[]} ]
    data_string = json.dumps(data, cls=DjangoJSONEncoder)
    return HttpResponse(data_string, mimetype='application/json')

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

而不是使用filter,您似乎需要使用select_related,以便查询也可以获取该数据。

根据您的代码,您只需要在循环中更改一行:

items = CartItem.objects.select_related('product').filter(cart=cart)