インスタンスモデルの前に関連モデルインスタンスを保存する方法。モデルインスタンスの前に関連するモデルインスタンスをdjangoに保存するには?
モデルインスタンスsave
メソッドの下で、関連するモデルのインスタンスフィールドを前処理したいので、これは必要です。
私はDjangoプロジェクトに取り組んでいます。インスタンスの関連するモデルがすべてデータベースに保存された後、私はいくつかの機能を実行する必要があります。
レッツは、私がモデル
ビデオモデルの新しいインスタンスが作成されmodels.py
from . import signals
class Video(models.Model):
"""Video model"""
title = models.CharField(
max_length=255,
)
keywords = models.ManyToManyField(
KeyWord,
verbose_name=_("Keywords")
)
を持っていると言います。
私は が必要です。1.関連するすべてのモデルが最初に保存されます。 a。関連するモデルが空の場合は、空または空の戻り値 を入力し、このビデオインスタンスを保存します。
私はpost_save
シグナルを使ってやろうとしましたが、関連モデルが最初にモデルに保存されるという保証はないので、成功することはできませんでした。
from django.db.models.signals import post_save, pre_delete, m2m_changed
from django.dispatch import receiver
from .models import Video
@receiver(m2m_changed, sender=Video)
@receiver(post_save, sender=Video)
def index_or_update_video(sender, instance, **kwargs):
"""Update or create an instance to search server."""
# TODO: use logging system
# Grab the id
print("Id is", instance.id)
# Keywords is empty as keyword instance is saved later than this instace.
keywords = [keyword.keyword for keyword in instance.keywords.all()]
print(keywords) # [] empty no keywords
instance.index()
@receiver(pre_delete, sender=Video)
def delete_video(sender, instance, **kwargs):
print("Delete index object")
instance.delete()
更新:
がpost_save
信号をつかんで実装してunitlsを待つことができます その関連モデルはDBに保存されます、related_modelsをシリアル化プロセスを開始し、一緒にフラットJSONファイルを作成 保存取得するときモデルフィールドとそれに関連するインスタンスのため、フラットjsonファイルは を弾性検索サーバーにインデックスできます。
質問欄では、シグナルハンドラメソッドでどのくらい時間を待つ必要がありますか?インスタンス関連のフィールドをすべて知る方法をdbに保存しました。
class Video(models.Model):
def save(self, *args, **kwargs):
# 1. Make sure all of its related items are saved in db
# 2. Now save this instance in db.
# 3. If the model has been saved. Serialize its value,
# 4. Serailize its related models fields
# 5. Save all the serialized data into index server
# The advantage of using this is the data are indexed in real
# time to index server.
# I tired to to implement this logic using signals, in case of
# signals, when the instance get saved, its related models are
# not instantly available in the databse.
# Other solution could be, grab the `post_save` signals, wait(delay
# the serialization process) and start the serialization of
# instance model and it's related to convert the data to flat json
# file so, that it could index in the searching server(ES) in real
# time.
# until the instance related models get saved and start to
# serialize the data when its
キーワードフィールドまたは文字列にキーワードインスタンスを渡していますか? – scriptmonster
@scriptmonsterキーワードインスタンス – shining