Change: Saving ManyToMany Relationships

created on Oct. 24, 2012, 11:29 p.m. by Hevok & updated on Oct. 24, 2012, 11:29 p.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: ::

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)

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

Tags: m2m, save, django
Categories: Tutorial
Parent: Web Framework

Comment: Created entry.

See entry | Admin

Comment on This Data Unit