David542
David542

Reputation: 110277

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

Upvotes: 0

Views: 217

Answers (1)

Udi
Udi

Reputation: 30522

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.

Upvotes: 1

Related Questions