我有这个简单的函数来从数据库中检索数据:
function find_object() {
$.ajax({type: 'POST',
url: '/find-object/',
data: {
position: position,
},
success: function (result_list) {
if (result_list.result === 'OK') {
console.log(result_list.data.myobject)
} else {
console.log('not found')
};
}
});
};
这里是view:
def find_object(request):
if request.is_ajax():
position = request.POST.get('position', None);
try:
my_object=My_Class.objects.get(coordinate=position)
except:
return JsonResponse({'result': 'None'})
my_other_object=My_Other_Class.objects.filter(my_ForeignKey_field=my_object)
if my_related_object:
my_field=my_other_object.my_field
#do things
return JsonResponse({'result': 'OK', 'data': { 'myobject': my_object }})
它给出了错误my_object is not JSON serializable,因为它不是一个查询集,因为它来自.get()所以我不能像这样序列化:
my_object_json=serializers.serialize('json', my_object)
在我使用的第一个请求中,.get()因为它比.filter()(当异常罕见时)更快。对于每个position只有一个my_object或(很少)没有。在我使用的第二个请求中,.filter()因为异常并不罕见。
所以问题:
.filter()1)使用它是否更快.get(),然后my_object像上面那样序列化还是有其他方法?也许没有 JsonResponse?我需要包含所有字段的对象
2)是 ForeignKeymy_other_object类的一个实例。my_object我想要的是?如果my_object存在,我想看看是否存在通讯员my_other_object并找到他的一个字段的值。对于每个my_object只有一个my_other_object或没有。我的解决方案有效,但也许有更快的方法。
另外:我应该使用 else 条件if request.is_ajax()吗?为什么不应该是ajax?
谢谢你