【问题标题】:Django model queryset changed into json serializable not workingDjango模型查询集更改为json可序列化不起作用
【发布时间】:2022-02-16 13:43:25
【问题描述】:

我在会话中保存了模型对象,如下所示,来自上下文处理器。

students = Student.objects.all()
studente = serializers.serialize('json', students)
request.session['students'] = students

在我的模型表单中

class NewIssueForm(forms.ModelForm):
    def __init__(self,*arg,students, **kwargs):
        super(NewIssueForm, self).__init__(*args, **kwargs)

        self.fields['borrower_id'] = students

我在尝试运行时遇到错误。

'''''
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated
    return self.render(context)
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 994, in render
    return render_value_in_context(output, context)
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 973, in render_value_in_context
    value = str(value)
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\html.py", line 376, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 132, in __str__
    return self.as_table()
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 270, in as_table
    return self._html_output(
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 198, in _html_output
    bf = self[name]
  File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 163, in __getitem__
    self._bound_fields_cache[name] = field.get_bound_field(self, name)
AttributeError: 'str' object has no attribute 'get_bound_field'

如何使该字段填充学生项目而不会出现错误?

【问题讨论】:

    标签: django django-sessions


    【解决方案1】:

    试试

    self.fields['borrower_id'].queryset = students
    

    【讨论】:

    • 如果 queryset 为 None 则 self._queryset = None 会出错 else queryset.all() AttributeError: 'set' object has no attribute 'all'
    猜你喜欢
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2019-09-25
    • 2021-04-28
    • 2019-12-27
    • 1970-01-01
    • 2021-11-27
    • 2012-09-12
    相关资源
    最近更新 更多