2011-06-12 88 views
0

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

你可以发布你的模型吗? – Udi 2011-06-12 18:05:39

+0

@Udi,我已更新以包含模型。 – David542 2011-06-12 22:25:59

回答

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中检查“save”或“add”键。

+0

@ Udi,谢谢你的回应。但是,如果用户有多个条目用于他的教育,该怎么办?例如,如果他有一个本科学校,然后是一所研究生院。它永远不会在用户之间共享,但用户可能有多个条目。另外,你是否参加过USC? – David542 2011-06-12 23:10:03

+0

@ David542,一个ForeignKey创建了一个多对一的关系。任何UserProfile可以有零个或多个教育实例。请参阅https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey。我没有参加USC,但HUJI。 – Udi 2011-06-12 23:23:35