Change - Saving ManyToMany Relationships

Created on Oct. 24, 2012, 11:29 p.m. by Hevok & updated on Oct. 25, 2012, 10:01 a.m. by Hevok

In order to save ManyToMany relationships of model (e.g. data tags of an entry), the respective clean field method of the model form can be overwritten like this: :: ¶

nano models.py ¶
from django.db import models ¶



class Tag(models.Mode): ¶
name = models.CharField(max_lengt=20) ¶


class Entry(models.Model): ¶
title = models.CharField(max_length=100) ¶
date = models.DateField() ¶
tags = models.ManyToManyField(Tag) ¶




nano forms.py ¶
from django.forms import models ¶


from models import Entry, Tag ¶




class EntryForm(models.ModelForm): ¶


def clean_tags(self): ¶
tags = self.cleaned_data.get('tags', None) ¶
clean_tags = [] ¶
tags = [tag.sprit() for tag in tags.split(',') if tags] ¶
for tag in tags: ¶
t, created = Tag.objects.get_or_create(title=tag) ¶
t.count = F('count') + 1 ¶
t.user.add(self.cleaned_data['user']) ¶
t.save() ¶
clean_tags.append(t) ¶
return clean_tags ¶


class meta: ¶
model = Entry ¶

Alternatively the model form save method an be overwritten if super is called: :: ¶

nano models.py ¶
... ¶
def save(self, commit=True): ¶
tags = [] ¶
for t in self.cleaned_data['tags'].split(','): ¶
tags.append(Tag.objects.get_or_create(name=t)[0]) ¶
e = super(EntryForm, self).save(commit=commit) ¶
for t in tags: ¶
e.tags.add(t)

Tags: m2m save django

Comment: Added alternative way.

Comment on This Data Unit