更新M2M关系

时间:2011-06-12 01:39:31

标签: django django-models django-forms

有没有办法直接更新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)

1 个答案:

答案 0 :(得分:1)

Education可能是个人UserProfile的个人信息,因此您应该使用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,则一个用户不应该修改/更新它 - 因为其他用户也在使用它!考虑用户Alice和Bob,他们都在2011年的USC课程中学习BSc。如果Alice将其更改为MA,Bob教育也会改变!

另一个提示:在您的模板中使用<input type="submit" name="save" value="..."/><input type="submit" name="add" value="..."/>,并在if检查“保存”或“添加”键。