How to work with unsaved many-to-many relationships in django?

I have a couple of models in django that are many-to-many related. I want to create instances of these models in memory, present them to the user (via custom method calls inside the presentation templates), and if the user is satisfied, save them in the database.

However, if I try to do something in the model instances (for example, call rendering methods), I get an error message stating that I have to save the instances first. The documentation says that this is due to the fact that the models are in many ways.

How to present objects to the user and allow him to save or discard them without cluttering my database?

(I think I could turn off transaction processing and execute them myself throughout the project, but that sounds like a potentially error-prone measure ...)

thanks!

+5
source share
3 answers

I think using django forms might be the answer as described in this documentation (search m2m ...).

Edited to add some explanation to other people who may have the same problem:

let's say you have a model like this:

from django.db import models
from django.forms import ModelForm

class Foo(models.Model):
    name = models.CharField(max_length = 30)

class Bar(models.Model):
      foos = models.ManyToManyField(Foo)

  def __unicode__(self):
      return " ".join([x.name for x in foos])

then you cannot call unicode () on an unsaved Bar object. If you want to print everything before they are saved, you must do this:

class BarForm(ModelForm):
    class Meta:
        model = Bar

def example():      
    f1 = Foo(name = 'sue')
    f1.save()
    f2 = foo(name = 'wendy')
    f2.save()
    bf = BarForm({'foos' : [f1.id, f2.id]})
    b = bf.save(commit = false)
    # unfortunately, unicode(b) doesn't work before it is saved properly,
    # so we need to do it this way: 
    if(not bf.is_valid()):
        print bf.errors
    else:
        for (key, value) in bf.cleaned_data.items():
            print key + " => " + str(value)

, Foo ( , ), , , . ...

+4

, , "" "". , , .., django .

, "" "" , . , "" ( ).

+6

, wagtail Django django-modelcluster. , CMS.

- ( README):

from modelcluster.models import ClusterableModel
from modelcluster.fields import ParentalKey

class Band(ClusterableModel):
    name = models.CharField(max_length=255)

class BandMember(models.Model):
    band = ParentalKey('Band', related_name='members')
    name = models.CharField(max_length=255)

:

beatles = Band(name='The Beatles')
beatles.members = [
    BandMember(name='John Lennon'),
    BandMember(name='Paul McCartney'),
]

ParentalKey Django ForeignKey. ParentalManyToManyField Django ManyToManyField.

0

All Articles