marshmallow-code / marshmallow-code/marshmallow-sqlalchemy

Issue with association object with primary key composed of two foreign keys

Open
#264 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Hi,

I have an issue with my data structure. Not sure if it's a bug, or (more probably), something that could be solved by tweaking the shema.

I have two objects, let's call them A and B, and an assotiation object A_to_B with a quantity.
This association object's primary key is composed of the foreign keys of A and B

We receive data as nested : A containing A_to_B containing B :
```
"a" : {
"id": a_id,
// other A data

b_data: {
quantity: 1,
b: {
"id": b_id,
// B data
}
}
```

The first time I load the data, everything works fine.
But the issue is that when trying to re-load existing data, sqlalchemy tries to delete the existing A_to_B (and to recreate it afterward).

It seems for some reason, marshmallow-sqlalchemy doesn't realize the association object is the same than the one that exists in the base.
Also at time of merge, sqlalchemy doesn't realize either, and removes the old instance to re-create the same thing.

For now the association schema looks like this :
```
class AToBSchema(BaseSchema):
b = Nested(BSchema)
class Meta(BaseSchema.Meta):
model = AToB
```

Any idea to prevent this unnecessary new instance ? (with a deletion of the old one)

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 with the AToBSchema definition and the nested A/B data shown in the issue, then reproduce loading the same data twice and inspect the SQLAlchemy merge behavior. Done means reloading an existing association object with a composite foreign-key primary key does not delete and recreate it unnecessarily.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlalchemy
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.