0

django/satchmo を継承した JPiece というモデル Product で pre_save シグナルを実行しました。また、satchmo カテゴリからの別のモデル継承である JewelCategory を持っています。pre_save シグナルにより、JPiece オブジェクトはカテゴリ リストを取得し、Jpiece の説明に適合するカテゴリをリレーションに追加します。これはモデルで行われます。つまり、手動で行う場合

p = Jpiece.objects.get(pk=3) p.save()

カテゴリは保存され、p.category m2m 関係に追加されますが、管理者から保存すると、これは行われません...

どうすればこれを達成できますか...管理者からJPieceを保存し、それが属するカテゴリも取得するには...

以下のモデルは、どちらも satchmo の製品クラスとカテゴリ クラスからモデルを継承していることを覚えています。

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)

必要なものについて説明が曖昧な場合があることは承知していますので、何でもお気軽にお尋ねください。これは緊急に必要なクライアントであるため、できるだけ早く明確にするようにしてください.

いつもありがとうございます。

4

1 に答える 1

1

を使用すると、 beforepre_saveが呼び出されます。つまり、モデルに ID がないため、m2m 関係を定義できません。 save()

を使用しpost_saveます。

# this works because the ID does exist
p = Jpiece.objects.get(pk=3) 
p.save()

更新、ここのコメントをチェックしてください: Django - post_save シグナルを介して m2m データを保存する方法?

現在の原因は、管理フォームでは、データをsave_m2m()上書きpost_saveする可能性のある信号の後に発生しているようです。のフォームからフィールドを除外できますModelAdminか?

# django.forms.models.py
if commit:
    # If we are committing, save the instance and the m2m data immediately.
    instance.save()
    save_m2m()
于 2011-03-17T22:19:52.687 に答える