2016-05-22 68 views
0

我想在模型的.save()方法期間基於用戶輸入創建其他對象。信息存儲在ManyToMany關係.available_specs中。Django ManyToMany在save()函數中訪問

我的代碼工作,如果按下保存兩次,但不是在第一次。這個問題在Django foreign key access in save() function的評論中也有描述。

這裏是我做的:

def save(self, *args, **kwargs): 

    my_save_result = super().save(*args, **kwargs) #save first to create an id 
    self.refresh_from_db() #just as a test, did not help at all 

    #the following line is the problem: 
    # in the first save, available_specs.all() returns [] 
    # when I re-open the model and save again, I get the correct list 
    for spec in self.available_specs.all(): 
     VehicleSpec.objects.get_or_create(vehicle=self, spec=spec) 

    return my_save_result 

我使用Python 3.5和1.9的Django

編輯: 我試着用下面的代碼(使用post_save()信號並刪除了重寫保存() - 方法):

@receiver(post_save, sender=VehicleModel) 
def create_dependent_vehicle_specs(sender, **kwargs): 
    vehicle = kwargs['instance'] 

    #in the first save-process I get an empty list here, 
    #after I hit save again, the code works. 
    print(vehicle, vehicle.available_specs.all()) 
    for spec in vehicle.available_specs.all(): 
     VehicleSpec.objects.get_or_create(vehicle=vehicle, spec=spec) 

EDIT2: m2m_changed的伎倆:

@receiver(m2m_changed, sender=VehicleModel) 
def create_dependent_vehicle_specs(sender, **kwargs): 
    vehicle = kwargs['instance'] 
    for spec in vehicle.available_specs.all(): 
     VehicleSpec.objects.get_or_create(vehicle=vehicle, spec=spec) 

m2m_changed.connect(create_dependent_vehicle_specs, sender=VehicleModel.available_specs.through) # @UndefinedVariable 

BTW:一個相關的問題是在這裏:Django accessing ManyToMany fields from post_save signal

+0

您是否嘗試在['post_save']中執行此操作(https://docs.djangoproject.com/en/1.9/ref/signals/#post - 保存)信號? – ozgur

+0

我剛剛嘗試過,效果相同 – OBu

回答

2

您需要使用m2m_changed signal。您不應該在其他模型的另存爲get_or_create保存方法

+0

非常感謝我指出了這一點 – OBu