marshmallow-code / marshmallow-code/marshmallow-sqlalchemy

Fail if Related can't find an existing record.

Open
#212 8 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

help wanted
Dominant language
Python
Stars
580
Forks
101
Avg merge
7h 6m
Merged PRs (30d)
3

Description

I'd like to be able to tell the Related field that it should fail if it can't find an existing parent record. This is for when a user doesn't have the ability to add parent records and I want to let them know that the record they are specifying does not exist yet.

Something like this in Related's deserialize method?

```python
try:
result = self._get_existing_instance(
self.session.query(self.related_model), value
)
except NoResultFound:
# The related-object DNE in the DB, but we still want to deserialize it
# ...perhaps we want to add it to the DB later
if self.create:
return self.related_model(**value)
raise ValidationError("Related record does not exist")
return result
```

At the moment, I have to accomplish this via a @validates() decorator in the schema that performs this check, like so:

```python
class WorkflowSchema(marsh.ModelSchema):
class Meta:
ordered = True
model = Workflow
strict = True
dump_only = ("id", "created_at", "updated_at")
exclude = ("jobs",)

team = Related(column="name")
workflow_template = Related(column="name")
parameters = fields.Dict()

@validates("workflow_template")
def validate_workflow_template(self, input):
name = input.name
try:
WorkflowTemplate.query.filter_by(name=name).one()
except NoResultFound:
raise ValidationError(f"Workflow template '{name}' does not exist")
```

Thoughts?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading Related.deserialize and its _get_existing_instance call, then compare the proposed NoResultFound handling with the existing @validates example. The change should let create-enabled relations deserialize new objects while raising ValidationError when creation is disabled and the related record does not exist; add or update coverage for both paths.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlalchemy
Domain
databases
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.