[英]How to get the fields of Foreign key field in a queryset
I have the following models: 我有以下型号:
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)
I want to get a JSON of all the cartItems in a cart (where is_check_out =False), and for that i have the following code: 我想获得购物车中所有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')
This gives me the following JSON: 这给了我以下JSON:
[
{
"items": [
{
"product": 48,
"price": "0.69",
"tax": "0.09",
"cart": 169,
"note": null,
"id": 467,
"quantity": 1
}
],
"cart_id": 169
}
]
But what i am looking for is something like : 但是我正在寻找的是这样的:
[
{
"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
}
]
UPDATE: I changed my get_user_cart
to the following to achieve what i was looking for; 更新:我将get_user_cart
更改为以下内容,以实现所需的功能; if there is a better way of doing this please comment or answer. 如果有更好的方法,请发表评论或回答。
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')
Any help is appreciated 任何帮助表示赞赏
Instead of using filter
, it would appear that you need to use select_related
so that the query gets that data as well. 似乎没有使用filter
,而是需要使用select_related
以便查询也可以获取该数据。
Based on your code, you only need to change one line in the loop: 根据您的代码,您只需要在循环中更改一行:
items = CartItem.objects.select_related('product').filter(cart=cart)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.