python - Safely persisting django models with foreign keys -
i implemented storage of one-to-many models through view. model structure follows:
- a dagrun model
- many dagrunmodel, have fk dagrun
- many dagmodelparam, have fk dagrunmodel
so follows, create instances first, make sure there no errors, , in end, persist them using save(). returns
django.db.utils.integrityerror: not null constraint failed: [28/jul/2017 11:56:12] "post /task/run http/1.1" 500 19464 and code of how create models , persist them in end
def task_run(request): dag_task = none dag_tasks = dagtask.objects.filter(dag_id=request.post["task"]) if len(dag_tasks) > 0: dag_task = dag_tasks[0] else: raise valueerror("task name not valid dag id") dag_run = dagrun( dag_task=dag_task, database=request.post["database"], table=request.post["table"], label=request.post["label"], features=request.post["features"], user=request.user, date=timezone.now() ) dag_params = [] dag_models = [] models = json.loads(request.post["models"]) model in models: dag_run_model = dagrunmodel( dag_run=dag_run, dag_model=model["name"] ) dag_models.append(dag_run_model) param in model["params"]: dag_param = dagrunparam( dag_run_model=dag_run_model, dag_param=param["name"], param_value=param["value"] ) dag_params.append(dag_param) dag_run.save() dag_model in dag_models: dag_model.save() dag_param in dag_params: dag_param.save() if instead decide save them create them, code works fine. looks foreign keys can used once models persisted, , might risked if models fail created later in hierarchy.
is there safer approach?
you may want use transaction can enforce "everything gets saved or nothing does" type of behavior. safest approach in opinion.
Comments
Post a Comment