3

i'm having an annoying issue with django model system + its default admin.

Let's assume i have a very simple model like:

class Note(models.Model):
    text = models.CharField(max_length=200)

def __unicode__(self):
    return self.text

and a container like:

class NoteCollection(models.Model):
    notelist = models.ManyToManyField(Note)
    title = models.CharField(max_length=20)

def __unicode__(self):
    return self.title

What i want do to it's update all the "Note" elements when a NoteCollection gets Added. I read that m2m models have complex save mechanism, so what i was thinking is, let's read the form object, and just save the Note elements by myself!!

But when i make something like this in APPNAME/admin.py:

from models import Note,NoteCollection
from django.contrib import admin

class NoteCollectionAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # Something USEFUL HERE
        pass

admin.site.register(Note)
admin.site.register(NoteCollection, NoteCollectionAdmin)

Django pops me an error: ('NoteCollection' instance needs to have a primary key value before a many-to-many relationship can be used.)

I don't even want to use the NoteCollection object at all, i'm interested in the form object, actually..

I've also found on internet some examples that use save_model with a M2M field, so i can't understand why i keep getting this error; for reference, i've just made a new-from-scrap project and i'm using an sqlite db for testing

Valerio
  • 2,390
  • 3
  • 24
  • 34

1 Answers1

2

By overriding save_model() in NoteCollectionAdmin you're preventing Django from saving your notecollection. After handling everything, Django saves the m2m table, but fails because the notecollection doesn't have an automatic ID as you didn't save it in the database.

The main problem is that Django saves m2m files after saving the objects. I tangled with that a few days ago, see http://reinout.vanrees.org/weblog/2011/11/29/many-to-many-field-save-method.html

Somewhat related question: Issue with ManyToMany Relationships not updating inmediatly after save

Community
  • 1
  • 1
Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68