Django ManyToMany access in save() function
我想在我的模型的.save()方法期间基于用户输入创建其他对象。该信息存储在多个关系
如果有人按两次save,我的代码就可以工作,但第一次不行。这个问题也在save()函数中的django foreign key access注释中描述。
我要做的是:
1 2 3 4 5 6 7 8 9 10 11 12 | 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和django 1.9
编辑:我尝试使用以下代码使用
1 2 3 4 5 6 7 8 9 | @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_变戏法了:
1 2 3 4 5 6 7 | @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从post-save信号访问许多字段
您需要使用