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

Python 如何获取查询集中外键字段的字段,python,django,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 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(其中是\u check\u 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\u user\u 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')

非常感谢您提供的任何帮助

而不是使用
过滤器
,您似乎需要使用它,以便查询也能获取该数据

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

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

我以前试过,但没用。序列化项目后,产品的值为其id