I'm developing an Ajax query to Django and works fine, returns the correct value but when I want to access the info I get this error:
SyntaxError: missing name after . operator
I returned the information query with these lines in python file:
attributes = MyModel._meta.get_fields()
objects = MyModel.objects.all()
data = serializers.serialize('json', objects, fields=(attributes[1].name))
print(data)
return HttpResponse(data, content_type='application/json')
print(data) output:
[{
"model": "contenttypes.contenttype",
"pk": 11,
"fields": {
"model": "accountingseat"}
},
{
"model": "contenttypes.contenttype",
"pk": 12,
"fields": {
"model": "bill"
}
}]
javascript file:
function functionName(param) {
for (var i = 0; i < param.length; i++) {
console.log(param[i]);
console.log(param[i].pk);
var fields = param[i]['fields'];
for (var x = 0; x < fields.length; x++) {
console.log(fields.[x]); //error line
}
}
}
console.log() output:
Object { model: "general.module", pk: 1, fields: { name: "General" } }
The problem is that I can't access with name because name of attribute change in each model.
How can i access to fields? Thanks in advance.
If I understand your question correctly, then this can be resolved by using Object.values()
like so:
function functionName(param) {
for (var i = 0; i < param.length; i++) {
console.log(param[i]);
console.log(param[i].pk);
var fields = param[i]['fields'];
// Object.values throws expection if undefined passed so check this first
if(fields) {
// Access the values of the fields object if valid
var fieldsValues = Object.values(fields);
for (var x = 0; x < fieldsValues.length; x++) {
console.log(fieldsValues[x]);
}
}
}
}