[英]Django ajax response model
I need to get data in template. 我需要在模板中获取数据。
I have ajax request: 我有一个ajax请求:
$(".retailer-list-img").mouseover(function () {
var $this = $(this);
var category_id = $this.attr('id');
$.ajax({
'url': '/shop/getfeatured/',
'method': 'POST',
'data': {'category_id': category_id,},
'success': function(response){
console.log(response)
}
});
});
views.py views.py
def MerchantGetfeaturedView(request):
featured = Merchant.objects.filter(
is_catalog_active=1,
is_active=1,
category_id=request.REQUEST.get('category_id'),
date_deleted__isnull=True
).select_related('_image')
featured = serializers.serialize('json', featured)
return HttpResponse(featured, content_type="application/json")
But there is no related object "image"? 但是没有相关的对象“图像”吗? How to serialize related model? 如何序列化相关模型? Thanks. 谢谢。
First, you have to transform your object. 首先,您必须变换对象。
result = { 'is_catalog_active': featured['is_catalog_active']
'is_active': 1,
'category_id': int(request.REQUEST.get('category_id')),
'image_id' : _image.id,
'image_name': _image.name
}
You can have PyCharm to help you auto-complete related model field. 您可以使用PyCharm来帮助您自动完成相关的模型字段。 Random guessing sometimes is bad, if you have right tool. 如果您拥有合适的工具,则随机猜测有时会很不好。 Alternatively, check django document for further investigation. 或者,检查Django文档以进行进一步调查。
Secondly, $.ajax() function don't have fail callback, so the pattern is not complete. 其次,$ .ajax()函数没有失败回调,因此模式不完整。 In reality, user have to know front end feed back. 实际上,用户必须知道前端反馈。 eg which type of error. 例如哪种类型的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.