我开始注意到patch
django rest框架中的方法实际上并未触发信号,post
方法似乎可以正常工作。这就是我所拥有的:
@receiver(signals.pre_save, sender=Example)
def populate_time_fields_based_on_state(sender, **kwargs):
example = kwargs.get('instance')
if example.start_datetime is None and example.projected_end_datetime is None and example.state.label == 'Assigned':
example.start_datetime = datetime.datetime.now()
example.projected_end_datetime = example.created_datetime + datetime.timedelta(
days=example.som_field)
example.save()
我正在通过以下方式对此进行测试:
client = APIClient()
client.patch(f'/api/example/1/', {'state': 'Assigned'})
有没有办法告诉它触发信号?我需要在序列化程序中覆盖update方法吗?我正在尝试:
def partial_update(self, request, *args, **kwargs):
response = super().partial_update(request, *args, **kwargs)
instance = self.get_object()
instance.save()
return response
但这很hacky
在您的应用目录中,应该有一个apps.py
,有关格式请参阅文档。
通常,最终结果如下图所示,而不是他们手动连接信号的示例。请注意,我在这里具有“ project / apps /”结构,但是只需根据文件实际所在的位置更改模块名称即可:
#project/apps/my_app/__init__.py
default_app_config = 'project.apps.my_app.apps.MyAppConfig'
#project/apps/my_app/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = "project.apps.my_app"
verbose_name = "MyApp"
def ready(self):
from project.apps.my_app import signals
# ... other init &/or logging
注意:请随意删除init .py中的行,并name
在应用程序配置中使用。我不确定他们到底有多重要
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句