post_save strange behavior (at least to me!)

34 views
Skip to first unread message

Victor

unread,
Dec 5, 2014, 11:01:26 AM12/5/14
to django...@googlegroups.com
Django 1.7.1 and Apache2 in a production context.
I have the following situation
=================
models.py

class Items(models.Model):
code = models.CharField(primary_key=True,db_index=True,unique=True,max_length=20,db_column='code')
description = models.CharField(max_length=255)
supplier=models.ManyToManyField(Suppliers)
class Meta:
db_table = u'items'
post_save.connect(ItemSaveInAnotherDB, sender=Items, dispatch_uid="save_in_another_db")

class Suppliers(models.Model):
name = models.CharField(max_length=150, db_column='name', db_index=True)
address = models.CharField(max_length=255, db_column='address', blank=True,null=True)
class Meta:
db_table = u'suppliers'
=================
admin.py

class ItemsOption(admin.ModelAdmin):
search_fields=[('code','description', ('supplier')]
fields=('code','description')
filter_horizontal = ['supplier', ]
=================
signals.py

def ItemSaveInAnotherDB(sender, instance, **kwargs):
........
........
sup = instance.supplier.all()
print 'SUPPLIERS LIST'
for s in sup:
print s.name
........
........
return
=================


Let's suppose that I have an item with one supplier only: Donald Duck.
1) Now in the admin change form I add another supplier to the ManyToManyField, say 'Goofy', to the same item and click on save.
Well the ItemSaveInAnotherDB post_save signal shows the previous situation only

SUPPLIERS LIST
Donald Duck

2) But if in the change form, containing as before Donald Duck and Goofy, I click again on save (without changing anything, I mean)
the ItemSaveInAnotherDB signals shows correctly

SUPPLIERS LIST
Donald Duck
Goofy

I thought that the post_save signal in case 1) acted on the already saved record therefore in my poor opinion it should have shown both Donald Duck and Goofy.
Instead.... only re-saving the record the post_save signal as in case 2) it works correctly.

How can I avoid this and have the more updated list available at first shot?

Ciao
Vittorio







Collin Anderson

unread,
Dec 6, 2014, 1:02:16 PM12/6/14
to django...@googlegroups.com
Hi Vittorio,

ManyToMany fields are technically stored in a separate table in the database and are technically a separate "record" from the parent model. The parent model needs to be saved first (firing the post_save signal), and only then can the ManyToMany values be updated.

I'd override the save_model() or save_related() methods of ItemOptions.

Collin
Reply all
Reply to author
Forward
0 new messages