在Django视图中获取多选查询集并将其保存 [英] get a multiple choice queryset in Django view and save it
问题描述
我有一个带有外键的多选字段。我想保存哪个门将参加培训课程,我想将所有门将列为多选字段。
I have a multiple choice field with a foreign key. I want to save which keeper was attending a training session and I want to list all keepers as a multiple choice field.
class AddAttendance(forms.ModelForm):
attendanceKeeper = Attendance.objects.only("keeper","present").all()
keeperValues = Attendance.objects.values_list("keeper__id", flat=True).distinct()
keeper = forms.ModelMultipleChoiceField(widget=forms.widgets.CheckboxSelectMultiple, queryset=Keeper.objects.filter(id__in=keeperValues, status=1))
class Meta:
model = Attendance
fields = ('keeper',)
def __init__(self, *args, **kwargs):
super(AddAttendance, self).__init__(*args, **kwargs)
self.initial["keeper"] = Keeper.objects.all()
但是我的问题是,我不熟悉如何在视图中处理查询集,如何遍历查询集以及如何将每个实例保存为True或False。
However my problem is, I am not familiar how to handle a queryset in the view and how to loop through it and to save every instance with the value True or False.
我总是得到查询的值错误集合无法分配
I always get the value error that a queryset cannot be assigned
"Attendance.keeper" must be a "Keeper" instance
您能帮我如何访问查询集值并将其保存
Can you help me how I access the queryset values and save them
def new_attendance(request, team_pk, package_pk):
if request.method == "POST":
form = AddAttendance(request.POST)
if form.is_valid():
for item in form:
attendance = item.save(commit=False)
attendance.keeper = get_object_or_404(AddAttendance.keeper)
attendance.team = get_object_or_404(Team, pk=team_pk)
attendance.created_date = timezone.now()
attendance.save()
return redirect(reverse('select_package', args=[package_pk, team_pk]))
else:
form = AddAttendance()
return render(request, 'attendance/new_attendance.html', {'form': form})
最后我想从queryset中匹配keeper并将True / False(真/假)保存到模型中存在的字段中
In the end I want to match keeper from the queryset and save True/False into the field present in my model
class Attendance(models.Model):
session = models.ForeignKey(Session)
keeper = models.ForeignKey(Keeper)
team = models.ForeignKey(Team)
present = models.BooleanField()
created_date = models.DateTimeField(default=timezone.now)
edited_date = models.DateTimeField(default=timezone.now)
推荐答案
您不需要多选字段;您需要一个单个选择。每个考勤对象只能与一个管理者相关联。
You don't want a multiple choice field; you want a single choice. Only one keeper can be associated with each Attendance object.
您在这里正在做很多奇怪且不必要的事情。您应该删除大部分代码,并使用ModelChoiceField作为ForeignKey的默认值。您也不需要复选框小部件,因为这又是多重选择;
You are doing a bunch of strange and unnecessary things here. You should remove most of this code, and use the ModelChoiceField which is the default for a ForeignKey. You don't want a checkbox widget either, since again that is for multiple choices; perhaps a radiobutton would be suitable.
class AddAttendance(forms.ModelForm):
class Meta:
model = Attendance
fields = ('keeper',)
widgets = {'keeper': forms.RadioSelect}
# remove the __init__ and the field definitions, you don't need them
...
form = AddAttendance(request.POST)
if form.is_valid():
attendance = item.save(commit=False)
attendance.team = get_object_or_404(Team, pk=team_pk)
attendance.created_date = timezone.now()
attendance.save()
return redirect(reverse('select_package', args=[package_pk, team_pk]))
由于表单正在执行此操作,因此无需在视图中显式设置守护者。
There's no need to set the keeper explicitly in the view, since that's what the form is doing.
这篇关于在Django视图中获取多选查询集并将其保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!