gpt4 book ai didi

Django m2m表单保存 "through "表

转载 作者:行者123 更新时间:2023-12-03 01:52:46 27 4
gpt4 key购买 nike

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

我的代码:

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

在 View 中:

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

我应该如何初始化成员资格才能正确填充成员资格表?

最佳答案

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

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

form.save_m2m()

但如果使用中间表,您需要手动处理 POST 数据并创建包含所有必填字段的 Membership 对象 ( similar problem )。最基本的解决方案是将您的 View 更改为:

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具有某些含义的对象(r​​equest.POST['members'] 将始终返回一个对象!)。

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

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

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

关于Django m2m表单保存 "through "表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com