0

我有模型:

class SettingField(models.Model):
    name = models.CharField(max_length=200)
    value = models.TextField(max_length=200)

    [...]

class Setting(models.Model):
    setting_type = models.CharField(max_length=1, choices=STYPES)
    fields = models.ManyToManyField(SettingField, null=True)

    [...]

和形式:

class SettingsForm(forms.Form):
    login = forms.CharField(
        required=True,
        label=u'Login'
        )
    password = forms.CharField(
        widget=forms.PasswordInput,
        required=True,
        label=u'Password'
        )

鉴于我有:

if request.method == 'POST':
    form = SettingsForm(request.POST)
    if form.is_valid():
        setting = Setting()
        setting.setting_type = 'd'
        setting.save()
        for ff in form.fields:
            setting_field = SettingField()
            setting_field.name = ff
            setting_field.value = form.cleaned_data[ff]
            setting_field.save()
            setting.fields.add(setting_field)

这将存储设置与依赖于表单的自定义字段。但现在我想得到这些数据:

s_objs = Setting.objects.filter(setting_type='d')

logins = list()

for so in s_objs:
    logins.append({
        "login": so.fields.??? what here ???,
        "password": so.fields.??? what here ???
    })

怎么做?我可以使用循环并比较名称,但也许还有另一种方法。

4

1 回答 1

2

这将为您提供一个包含与 so 相关的所有字段的名称和值的 dict。

so.fields.all().values('name', 'value')

您不想经常访问数据库,因此请在 s_objs 上使用 prefetch_related:

s_objs = Setting.objects.filter(setting_type='d').prefetch_related('fields')
于 2013-09-24T23:00:20.910 回答