简体   繁体   English

在Django中向查询集添加值

[英]Adding a value to a queryset in Django

In my Django form I have a ModelChoiceField for employees, but I want a choice in the dropdown for 'all' employees. 在我的Django表单中,我有一个供员工使用的ModelChoiceField,但我想在下拉菜单中为“所有”员工选择。 What would be the best way to accomplish this? 做到这一点的最佳方法是什么?

employees = forms.ModelChoiceField(queryset=Employees.objects.all())

First attemptI tried 第一次尝试

employees = forms.ChoiceField(choices = Employees.objects.values())

but I get a 'too many objects to unpack' error 但出现“无法解包的对象太多”错误

Thanks 谢谢

Try this: 尝试这个:

employees = forms.ChoiceField(choices = [(emp['id'], emp['full_name']) 
            for emp in Employees.objects.values('id', 'full_name')])

The too many objects to unpack error raised because every cell of chioces must only contains two value similar below: 出现太多无法解包的对象的错误,因为每个chioceo单元格只能包含两个类似以下的值:

[(1, 'Eric Manson'), (2, 'Julia Rose'), (3, 'Saadi Khorshid'), ...]

But Employees.objects.values() unpacking all fields in dictionary form. 但是Employees.objects.values()字典形式解压缩所有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM