有没有办法直接更新M2M关系,除了删除old_object &然后添加new_object?更新M2M关系
这是我现在必须添加一个新的对象 -
if 'Add School' in request.POST.values():
form = EducationForm(request.POST)
if form.is_valid and request.POST['school']:
school_object = form.save()
profile.educations.add(school_object)
profile.save()
return redirect('edit_education')
而这正是我试图做的 -
if 'Save Changes' in request.POST.values():
form = EducationForm(request.POST)
if form.is_valid and request.POST['school']:
new_school_object = form.save(commit=False)
old_school_object = Education.objects.get(id = request.post['id'])
# profile.educations.get(old_school_object).update(new_school_object) # ?
profile.save()
return redirect('edit_education')
,这里是我的模型 -
class Education(models.Model):
school = models.CharField(max_length=100)
class_year = models.IntegerField(max_length=4, blank=True, null=True, choices=YEAR)
degree = models.CharField(max_length=100, blank=True, null=True)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
...
educations = models.ManyToManyField(Education)
你可以发布你的模型吗? – Udi 2011-06-12 18:05:39
@Udi,我已更新以包含模型。 – David542 2011-06-12 22:25:59