有没有一种方法可以直接更新M2M关系,而不是删除old_object,然后添加new_object?
这就是我现在要添加的新对象--
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)发布于 2011-06-13 06:47:44
对于一个UserProfile来说,Education可能是个人化的东西,所以你应该使用ForeignKey而不是M2M:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
...
class Education(models.Model):
user_profile = models.ForeignKey(UserProfile)
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)(也可以选择使用模型表单集:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets )
如果Education实际上是在用户之间共享的,那么一个用户应该不可能修改/更新它--因为其他用户也在使用它!以用户爱丽丝和鲍勃为例,他们都是2011届南加州大学BSc的学生。如果Alice将其更改为MA,那么Bob的教育也将改变!
另一个提示:在你的模板中使用<input type="submit" name="save" value="..."/>和<input type="submit" name="add" value="..."/>,在你的if中检查"save“或"add”键。
https://stackoverflow.com/questions/6319604
复制相似问题