我正试图通过Django从我的应用程序中取出。问题是当我通过序列化程序调用Order Detail时,我收到此错误:
TypeError at /api/customer/order/latest/
Object of type 'Product' is not JSON serializable
Request Method: GET
Request URL: http://localhost:8000/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Django Version: 1.10
Exception Type: TypeError
Exception Value:
Object of type 'Product' is not JSON serializable
我从这个模型中提取数据:
class OrderDetail(models.Model):
order = models.ForeignKey(Order, related_name='order_details')
product_size = models.ForeignKey(ProductSize)
quantity = models.IntegerField()
sub_total = models.FloatField()
def __str__(self):
return str(self.id)
# references Prodcut and allows old code to work.
@property
def product(self):
return self.product_size.product
这就是被拉动的内容:
'order_details': [OrderedDict([('id', 68),
('product_size', 44),
('quantity', 1),
('sub_total', 20.0),
('product', <Product: Bacon Burger - withDrink>)])],
'status': 'Your Order Is Being Picked Right Off The Plant!',
'total': 20.0}
request
<WSGIRequest: GET '/api/customer/order/latest/?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX'>
串行器:
class OrderDetailSerializer(serializers.ModelSerializer):
class Meta:
model = OrderDetail
fields = ("id", "product_size", "quantity", "sub_total", "product")
class OrderSerializer(serializers.ModelSerializer):
customer = OrderCustomerSerializer()
driver = OrderDriverSerializer()
restaurant = OrderRestaurantSerializer()
order_details = OrderDetailSerializer(many = True)
status = serializers.ReadOnlyField(source= "get_status_display")
class Meta:
model = Order
fields = ("id", "customer", "restaurant", "driver", "order_details", "total", "status", "address")
详情功能:
def customer_get_latest_order(request):
access_token = AccessToken.objects.get(token = request.GET.get("access_token"),
expires__gt = timezone.now())
customer = access_token.user.customer
order = OrderSerializer(Order.objects.filter(customer = customer).last()).data
return JsonResponse({"order": order})
我不确定需要做什么。
答案 0 :(得分:2)
由于db.users.aggregate([
{
$lookup:{ // lookup assigned tickets
from:'tickets',
localField:'assignedTickets',
foreignField:'_id',
as:'assigned',
}
},
{
$lookup:{ // lookup resolved tickets
from:'tickets',
localField:'resolvedTickets',
foreignField:'_id',
as:'resolved',
}
},
{
$project:{
"tickets":{ // merge all tickets into one single array
$concatArrays:[
"$assigned",
"$resolved"
]
}
}
},
{
$unwind:'$tickets' // flatten the 'tickets' array into separate documents
},
{
$group:{ // group by 'createdAt' and 'assignee_id'
_id:{
groupDate:{
$dateFromParts:{
year:{ $year:'$tickets.createdAt' },
month:{ $month:'$tickets.createdAt' },
day:{ $dayOfMonth:'$tickets.createdAt' },
},
},
userId:'$tickets.assignee_id',
},
assignedCount:{ // get the count of assigned tickets
$sum:{
$cond:[
{ // by checking the 'type' field for a value of 'assigned'
$eq:[
'$tickets.type',
'assigned'
]
},
1, // if matching count 1
0 // else 0
]
}
},
resolvedCount:{
$sum:{
$cond:[
{ // by checking the 'type' field for a value of 'resolved'
$eq:[
'$tickets.type',
'resolved'
]
},
1, // if matching count 1
0 // else 0
]
}
},
},
},
{
$sort:{ // sort by 'groupDate' descending
'_id.groupDate':-1
},
},
{
$group:{
_id:'$_id.userId', // group again but only by userId
data:{
$push:{ // create an array
groupDate:'$_id.groupDate',
assignedCount:{
$sum:'$assignedCount'
},
resolvedCount:{
$sum:'$resolvedCount'
}
}
}
}
}
])
模型的product
属性返回OrderDetail
个对象,因此在响应过程中无法序列化。
要解决此问题,您只需返回Product
:
product.id
或者,如果您需要回复产品的详细信息,则应在class OrderDetail(models.Model):
order = models.ForeignKey(Order, related_name='order_details')
product_size = models.ForeignKey(ProductSize)
quantity = models.IntegerField()
sub_total = models.FloatField()
def __str__(self):
return str(self.id)
@property
def product(self):
return self.product_size.product.id
中添加一个嵌套的序列化程序:
OrderDetailSerializer
答案 1 :(得分:1)
您需要为在OrderDetail模型中声明的product属性创建序列化程序。如果不这样做,它将给出此错误,因为product属性返回Product类的对象,并且它不知道如何序列化它。创建序列化程序后,请执行以下操作
class OrderDetailSerializer(serializers.ModelSerializer):
product=ProductSerializer(read_only=True, many=False)//you need to do this
class Meta:
model = OrderDetail
fields = ("id", "product_size", "quantity", "sub_total", "product")