I have the following issue with Django:
My model is defined as follows:
from django.db import models
class SettingSection(models.Model):
section = models.CharField(max_length=20)
def __unicode__(self):
return self.section
class SettingParam(models.Model):
section = models.ForeignKey(SettingSection)
param = models.CharField(max_length=20, unique=True)
description = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.param
class SettingPreset(models.Model):
preset = models.CharField(max_length=20, unique=True)
current = models.BooleanField()
def __unicode__(self):
return self.preset
class SettingValue(models.Model):
preset = models.ForeignKey(SettingPreset)
param = models.ForeignKey(SettingParam)
value = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return self.value
I have following error when trying to access any attribute of my SettingValue object:
>>> from settings.models import *
>>> preset = SettingPreset.objects.get(current=True)
>>> for section in SettingSection.objects.all():
... for param in section.settingparam_set.all():
... v = SettingValue.objects.filter(preset=preset, param=param)
... print v.id, v.value
...
Traceback (most recent call last):
File "<console>", line 4, in <module>
AttributeError: 'QuerySet' object has no attribute 'id'
However, the attributes ("id" and "value") seem to exist:
>>> for section in SettingSection.objects.all():
... for param in section.settingparam_set.all():
... v = SettingValue.objects.filter(preset=preset, param=param)
... print v.values()
...
[{'value': u'192.168.1.29', 'id': 1, 'preset_id': 1, 'param_id': 1}]
[{'value': u'en1', 'id': 2, 'preset_id': 1, 'param_id': 2}]
[{'value': u'0', 'id': 3, 'preset_id': 1, 'param_id': 3}]
[{'value': u'', 'id': 4, 'preset_id': 1, 'param_id': 4}]
[{'value': u'', 'id': 5, 'preset_id': 1, 'param_id': 5}]
In addition, I'm able to access any of the attributes without applying filters to my object:
>>> for v in SettingValue.objects.all():
... print v.id, v.value
...
1 192.168.1.29
2 en1
3 0
4
5
The variable v is a queryset, and you cannot access your models attributes via the queryset. Therefore you should try this to access the first element in your queryset:
for param in section.settingparam_set.all():
v = SettingValue.objects.filter(preset=preset, param=param)
print v[0].id, v[0].value #access first element in query set
Or do this to loop over the items in your queryset:
for param in section.settingparam_set.all():
v = SettingValue.objects.filter(preset=preset, param=param)
for item in v:
print item.id, item.value