I Have to loop through data of the query set in django and put the data into an array without specifying the model name.
My Django view:
permissions = Permission.objects.all().order_by('perm_label')
arrayData = []
for type in permissions:
for value in type:
arrayData.append(value)
This is giving me error:
Permission' object is not iterable
If I understand your question correctly, you could try this:
>>> from django.contrib.auth.models import Permission
>>> field_name_list = []
>>> qs = Permission.objects.all()
>>> qs = qs.filter(content_type__id=1) # I added this line to make this sample output shorter
>>> qs = qs.values(*field_name_list)
>>> final_data = []
>>> for elem in qs:
... print(type(elem))
... print(elem)
... for v in elem.values():
... final_data.append(v)
<class 'dict'>
{'id': 1, 'name': 'Can add log entry', 'content_type_id': 1, 'codename': 'add_logentry'}
<class 'dict'>
{'id': 2, 'name': 'Can change log entry', 'content_type_id': 1, 'codename': 'change_logentry'}
<class 'dict'>
{'id': 3, 'name': 'Can delete log entry', 'content_type_id': 1, 'codename': 'delete_logentry'}
>>> final_data
[1, 'Can add log entry', 1, 'add_logentry', 2, 'Can change log entry', 1, 'change_logentry', 3, 'Can delete log entry', 1, 'delete_logentry']
This uses the method queryset.values()
to have each Permission
instance be represented by a dict
instead of an actual model instance.
If you leave field_name_list
as an empty list, then you will get all fields for that model, but you can also add the names of the fields you want.
Then, you can use dict.values()
to just get the values (the column values for that row) without the keys (which would be the column names).