我对 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'
但是,属性(“id”和“value”)似乎存在:
>>> 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