我对Django有以下问题:
我的模型定义如下:
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
尝试访问我的SettingValue对象的任何属性时出现以下错误:
>>> 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'
然而,属性(&#34; id&#34;和&#34;值&#34;)似乎存在:
>>> 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}]
此外,我可以在不对我的对象应用过滤器的情况下访问任何属性:
>>> for v in SettingValue.objects.all():
... print v.id, v.value
...
1 192.168.1.29
2 en1
3 0
4
5
答案 0 :(得分:3)
变量v是一个查询集,您无法通过查询集访问模型属性。因此,您应该尝试使用它来访问查询集中的第一个元素:
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
或者这样做以循环查询集中的项目:
for param in section.settingparam_set.all():
v = SettingValue.objects.filter(preset=preset, param=param)
for item in v:
print item.id, item.value