如何从多个字段对象中获取数据?

时间:2019-04-30 06:33:24

标签: django django-models django-views many-to-many

我被困在模型中的许多字段对象中,我想从订单模型对象中检索产品价格,但是在获取商品价格时,有时会出现许多相关的经理错误或查询集错误

models.py

from django.db import models
from django.contrib import admin
from django.contrib.auth.models import User

class Product(models.Model):
    name = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    stock = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)



class Order(models.Model):
    user = models.ForeignKey(User,on_delete= models.SET_NULL,null = True)
    product = models.ManyToManyField('Order.Product')
    is_ordered = models.BooleanField(default =False)
    date_ordered = models.DateTimeField(auto_now = True,null = True)

views.py

def get_product_price(request):
    if request.method=="GET":
        user=User.objects.get(username = "hemant")
        orders = user.order_set.all()
        order = orders[0]   
        price = order.product.price
        return HttpResponse(price)

1 个答案:

答案 0 :(得分:0)

ManyToManyField获得价值时,您需要这样做:

products = order.product.all()

如果您想获取价格,可以这样做:

products = order.product.all()
for product in products:
    print(product.price)

如果您要返回价格作为http响应,则可以使用values_list()从queryset获取价格列表。像这样

import json


views.py
def get_product_price(request):
    if request.method=="GET":
        user=User.objects.get(username = "hemant")
        orders = user.order_set.all()
        order = orders[0]   
        price = list(order.product.all().values_list('price', flat=True))
        return HttpResponse(json.dumps(price))