-
Notifications
You must be signed in to change notification settings - Fork 1
Better error message from load_all_metadata - see HEA-572 #182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b4a6ba8
Better error message from load_all_metadata - see HEA-572
rhunwicks 04e1676
Remove unused exception variable from load_metadata_for_model - see H…
rhunwicks 73b51dd
Minor fix to load_all_metadata - see HEA-572
rhunwicks c8bec4e
Clearer specification of metadata upload fields - see HEA-572
rhunwicks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ | |
| from io import BytesIO | ||
|
|
||
| import django | ||
| import numpy as np | ||
| import pandas as pd | ||
| import requests | ||
| from dagster import OpExecutionContext, job, op | ||
|
|
@@ -127,20 +128,46 @@ def load_metadata_for_model(context: OpExecutionContext, sheet_name: str, model: | |
| id_fields = "wealth_characteristic_label" | ||
| else: | ||
| id_fields = "code" | ||
| # Add primary keys if they are not already in the id_fields, | ||
| # so that we can save individual instances if required | ||
| if isinstance(id_fields, str): | ||
| id_fields = [id_fields] | ||
| if model._meta.pk.name not in id_fields: | ||
| keys_df = pd.DataFrame.from_records( | ||
| model.objects.all().values(model._meta.pk.name, *id_fields) | ||
| ) # NOQA: E501 | ||
| df = df.merge( | ||
| keys_df, | ||
| how="left", | ||
| on=id_fields, | ||
| ) | ||
| df[model._meta.pk.name] = df[model._meta.pk.name].replace(np.nan, None) | ||
| # Turn the dataframe into a set of unsaved model instances | ||
| instances = [] | ||
| for record in df.to_dict(orient="records"): | ||
| if isinstance(id_fields, str): | ||
| id_fields = [id_fields] | ||
|
|
||
| record = {k: v for k, v in record.items() if k in valid_field_names} | ||
| instances.append(model(**record)) | ||
| instances = model.objects.bulk_create( | ||
| instances, | ||
| update_conflicts=True, | ||
| update_fields=[k for k in record if k not in id_fields], | ||
| unique_fields=id_fields, | ||
| ) | ||
| context.log.info(f"Created or updated {len(instances)} {sheet_name} instances") | ||
| try: | ||
| instances = model.objects.bulk_create( | ||
| instances, | ||
| update_conflicts=True, | ||
| update_fields=[k for k in record if k not in id_fields and k != model._meta.pk.name], | ||
rhunwicks marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| unique_fields=id_fields, | ||
| ) | ||
| context.log.info(f"Created or updated {len(instances)} {sheet_name} instances") | ||
| except Exception: | ||
| # Bulk create failed, so try creating/updating the instances one at a time to see which one failed | ||
| for i, instance in enumerate(instances): | ||
| try: | ||
| instance.save() | ||
| except Exception as e: | ||
| key = [getattr(instance, id_field) for id_field in id_fields] | ||
| instance = { | ||
| k: v for k, v in instance.__dict__.items() if k not in ["_state", "created", "modified"] | ||
| } | ||
| raise RuntimeError( | ||
| f"Failed to create/update {model_name} instance {i} {key} from:\n{json.dumps(instance, indent=4, ensure_ascii=False)}" | ||
|
||
| ) from e | ||
|
|
||
|
|
||
| @op | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider importing numpy only when needed (e.g.,
from numpy import nan) since numpy is a heavy dependency and only used fornp.nanreplacement on line 144.