开发者

Updating a M2M relationship

Is there a way to directly update a M2M relationship, other than by deleting the old_object & then adding a new_object?

This is what I currently hav开发者_JS百科e to add a 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')

And this what I'm trying to do --

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

And here are my models --

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)


Education is probably something personal to one UserProfile, so you should use a ForeignKey instead of 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)

(and optionally use model formsets: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets )

If Education is actually shared between users, it should not be possible for one user to modify/update it - since other users are using it as well! consider users Alice and Bob, both learning for BSc in USC class of 2011. If Alice changes this to MA, Bob education will change as well!

Another tip: In your templates use <input type="submit" name="save" value="..."/> and <input type="submit" name="add" value="..."/> and in your ifs check for the keys "save" or "add" instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜