0

如何在實例模型之前保存相關模型實例。如何在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。如果相關型號爲空,則返回空或無 2.然後保存此視頻實例。

我試圖使用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 其相關模型得到保存在數據庫中,當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 
+0

您是否將Keyword實例傳遞給關鍵字字段或字符串? – scriptmonster

+0

@scriptmonster關鍵字實例 – shining

回答

0

您可以在保存實例前覆蓋模型的save()方法並保存相關模型(對象)。

+0

我知道如何重寫save()方法,但是您能否告訴我一個覆蓋相關模型方法實例的示例 – shining

+0

您能舉出更多代碼嗎?你究竟在做什麼與相關的對象? –

+0

我已更新問題 – shining

0

通過我使用Django的管理員,我不限定 的邏輯視圖方式,增加了相關模型實例由Django管理

處理。在這種情況下,您可以翻轉ModelAdmin調用save_model()save_related()以便從Model.save()開始的順序,您將能夠達到相關字段的更新值,如this post中所述。

class Video(models.Model): 

    def save(self, *args, **kwargs): 
     if not self.id: 
      super().save(*args, **kwargs) 
     all_updated_keywards = self.keywards.all() 
     ... 
     super().save(*args, **kwargs) 


class VideoAdmin(admin.ModelAdmin): 

    def save_model(self, request, obj, form, change): 
     if not obj.pk: 
      super().save_model(request, obj, form, change) 
     else: 
      pass 

    def save_related(self, request, form, formsets, change): 
     form.save_m2m() 
     for formset in formsets: 
      self.save_formset(request, form, formset, change=change) 
     super().save_model(request, form.instance, form, change) 
相關問題