在Django视图中获取多项选择查询集并保存

时间:2018-06-03 08:43:13

标签: python django django-forms django-views django-queryset

我有一个带有外键的多选字段。我想保存哪个门将参加培训课程,我想列出所有饲养员作为多选领域。

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保存每个实例。

我总是得到无法分配查询集的值错误

"Attendance.keeper" must be a "Keeper" instance

您能帮助我如何访问查询集值并保存它们

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})

最后,我想与查询集中的守护者匹配,并将True / False保存到模型中的字段

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)

1 个答案:

答案 0 :(得分:0)

您不需要多选字段;你想要一个选择。只有一个守护者可以与每个出勤对象相关联。

你在做一些奇怪的和不必要的事情。您应该删除大部分此代码,并使用ModelChoiceField,它是ForeignKey的默认值。您也不需要复选框小部件,因为这也是多个选择;也许一个无线电按钮是合适的。

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]))

没有必要在视图中明确设置守护者,因为这就是表单的作用。