17

我无法保存包含“通过”类表的 m2m 数据。我想将所有选定的成员(在表单中选择)保存在直通表中。但我不知道如何在视图中初始化“通过”表。

我的代码:

class Classroom(models.Model):
     user = models.ForeignKey(User, related_name = 'classroom_creator')
     classname = models.CharField(max_length=140, unique = True)
     date = models.DateTimeField(auto_now=True)
     open_class = models.BooleanField(default=True)
     members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership')

class Membership(models.Model): 
      accept = models.BooleanField(User)
      date = models.DateTimeField(auto_now = True) 
      classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership')
      member = models.ForeignKey(User, related_name = 'user_membership')

在视图中:

def save_classroom(request):
   classroom_instance = Classroom()
   if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES, user = request.user) 
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user 
           new_obj.save()
           membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)

           membership.save() 

我应该如何初始化要填充的 Membership 表的成员资格?

4

4 回答 4

23

如果使用正常的 m2m 关系(不是通过中间表),您可以替换:

membership = Membership(member = HERE SELECTED ITEMS FROM FORM,classroom=new_obj)
membership.save()

form.save_m2m()

但是在使用中间表的情况下,您需要手动处理 POST 数据并创建具有所有必需字段的 Membership 对象(类似问题)。最基本的解决方案是将您的视图更改为:

def save_classroom(request):
    if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES)

        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user 
           new_obj.save()

           for member_id in request.POST.getlist('members'):
                membership = Membership.objects.create(member_id = int(member_id), classroom = new_obj)
           return HttpResponseRedirect('/')
    else:
        form = ClassroomForm()
    return render_to_response('save_classroom.html', locals())

注意 request.POST 是如何被操纵的(.getlist)。这是因为 post 和 get 是具有某些含义的QueryDict对象(request.POST['members'] 将始终返回一个对象!)。

您可以修改此代码以使其更可靠(错误处理等),更详细,例如:

member = get_object_or_404(User, pk = member_id)
membership = Membership.objects.create(member = member , classroom = new_obj)

但请注意,您正在循环中执行一些数据库查询,这通常不是一个好主意(就性能而言)。

于 2010-06-26T20:25:11.900 回答
5

就像 dzida 所做的一样,但使用 form.cleaned_data 而不是 request.post:

def save_classroom(request):
    if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES)

        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user
           new_obj.save()

           for member in form.cleaned_data['members'].all():
                Membership.objects.create(member = member,  classroom = new_obj)

           return HttpResponseRedirect('/')
    else:
        form = ClassroomForm()
    return render_to_response('save_classroom.html', locals())

您还需要考虑可能会删除某些成员资格,因此:

def save_classroom(request):
    if request.method == 'POST':
        form = ClassroomForm(request.POST, request.FILES)

        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.user = request.user
           new_obj.save()

           final_members = form.cleaned_data['members'].all()
           initial_members = form.initial['members'].all()

           # create and save new members
           for member in final_members:
                if member not in initial_members:
                    Membership.objects.create(member = member,  classroom = new_obj)

           # delete old members that were removed from the form
           for member in initial_members:
               if member not in final_members:
                   Membership.objects.filter(member = member, classroom = new_obj).delete()

           return HttpResponseRedirect('/')
    else:
        form = ClassroomForm()
    return render_to_response('save_classroom.html', locals())

如果您使用模型表单(例如在通用 CBV: 中form_class=ClassroomForm),请覆盖并将上面的保存逻辑放在save方法中,例如:

ClassroomForm(forms.ModelForm):
    members = ModelMultipleChoiceField(
        queryset=Classroom.objects.all(),
        widget=SelectMultiple
    )

    def save(self, commit=True):
        classroom = super().save(commit=False)
            if commit:
                classroom.save()
                if 'members' in self.changed_data:
                   final_members = self.cleaned_data['members'].all()
                   initial_members = self.initial['members']

                   # create and save new members
                   for member in final_members:
                        if member not in initial_members:
                            Membership.objects.create(member = member,  classroom = new_obj)

                   # delete old members that were removed from the form
                   for member in initial_members:
                       if member not in final_members:
                           Membership.objects.filter(member = member, classroom = new_obj).delete()

         return classroom
于 2016-11-26T20:19:06.033 回答
1

您还需要为成员指定教室:

membership = Membership(member = request.user,
                        classroom=new_obj) #if new_obj if your classroom
membership.save()

我想你也应该删除Userin accept = models.BooleanField(User)。如果您正在使用,则无需在保存时设置日期auto_now!但也许 `auto_now_add 更可能是您需要的(http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField

于 2010-06-19T11:14:12.693 回答
0

这就是我使用 form_valid 方法在基于类的通用 UpdateForm 视图(django 1.8)中为类似但不同的应用程序执行此操作的方式。

def form_valid(self, form):
    """
    If the form is valid, save the associated model.
    """
    self.object.members.clear()
    self.object = form.save(commit=False)
    self.object.user = self.request.user 
    self.object.save()

    list_of_members = form.cleaned_data['members']

    ClassRoom.objects.bulk_create([
            Membership(
                Course=self.object,
                member=member_person,
                order=num)
            for num, member_person in enumerate(list_of_members)
        ])
    return super(ModelFormMixin, self).form_valid(form)
于 2015-12-31T14:22:39.543 回答