Django autocategorize in m2m field
I have done a pre_save signal in my django/satchmo inherited model Product called JPiece and I have another model inheritance from satchmo Category called JewelCategory. The pre_save signal makes the JPiece objects get the category list and add those categories that fit the Jpiece description to the relation, that is done in the model, meaning if I manually do
p = Jpiece.objects.get(pk=3) p.save()
The categories are saved and added to the p.category m2m relation but If i save from the admin it does not do this...
How can I achieve this... to save from the admin a JPiece and to get the categories it belongs too...
Here are the models remember that they both have model inheritance from satchmo product and category classes.
class Pieza(Product):
codacod = models.CharField(_("CODACOD"), max_length=20,
help_text=_("Unique code of the piece. J prefix indicates silver piece, otherwise gold"))
tipocod = models.ForeignKey(Tipo_Pieza, verbose_name=_("Piece Type"),
help_text=_("TIPOCOD"))
tipoenga = models.ForeignKey(Engaste, verbose_name=_("Setting"),
help_text=_("TIPOENGA开发者_开发百科"))
tipojoya = models.ForeignKey(Estilos, verbose_name=_("Styles"),
help_text=_("TIPOJOYA"))
modelo = models.CharField(_("Model"),max_length=8,
help_text=_("Model No. of casting piece."),
blank=True, null=True)
def autofill(self):
#self.site = Site.objects.get(pk=1)
self.precio = self.unit_price
self.peso_de_piedra = self.stone_weigth
self.cantidades_de_piedra = self.stones_amount
self.for_eda = self.for_eda_pieza
if not self.id:
self.date_added = datetime.date.today()
self.name = str(self.codacod)
self.slug = slugify(self.codacod, instance=self)
cats = []
self.category.clear()
for c in JewelCategory.objects.all():
if not c.parent:
if self.tipocod in c.tipocod_pieza.all():
cats.append(c)
else:
if self.tipocod in c.tipocod_pieza.all() and self.tipojoya in c.estilo.all():
cats.append(c)
self.category.add(*cats)
def pieza_pre_save(sender, **kwargs):
instance = kwargs['instance']
instance.autofill()
# import ipdb;ipdb.set_trace()
pre_save.connect(pieza_pre_save, sender=Pieza)
I know I can be vague with explanations sometimes of what I need so please feel free to ask anything Ill be sure to clarify ASAP since this is a client that needs this urgently.
Thank you all as always...
If you use pre_save
, it's called before save()
, meaning you can't define m2m relationships since the model doesn't have an ID.
Use post_save
.
# this works because the ID does exist
p = Jpiece.objects.get(pk=3)
p.save()
Update, check out the comment here: Django - How to save m2m data via post_save signal?
It looks like the culprit now is that with an admin form, there is a save_m2m()
happening AFTER the post_save
signal, which could be overwriting your data. Can you exclude the field from the form in your ModelAdmin
?
# django.forms.models.py
if commit:
# If we are committing, save the instance and the m2m data immediately.
instance.save()
save_m2m()
精彩评论