Skip to content
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

JSON field data is not persisted correctly for SQLAlchemy JSON fields #1024

Open
aalvrz opened this issue May 31, 2023 · 1 comment
Open

Comments

@aalvrz
Copy link

aalvrz commented May 31, 2023

Description

Not sure if this is a Factory Boy bug or SQLAlchemy bug.

When trying to persist more complex dictionaries within a JSON field/column of a SQLAlchemy model, the data is only partially persisted.

Model / Factory code
# SQLAlchemy Model
from sqlalchemy import JSON


class Model:
    data = JSON()
import factory


# Factory
class ModelFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = Model
        sqlalchemy_session = Session
        sqlalchemy_session_persistence = "commit"
The issue

Set a more complex dictionary for the data JSON field when generating objects with the factory:

# Include the code that provoked the bug, including as full a stack-trace as possible

obj = ModelFactory(
  data={
    "apples": [
      {
        "apple_id": 1,
        "apple_color": "red",
      }
    ]
  }
)

The object is created, but the data field is persisted as:

{"apples": []}

Notes

SQLAlchemy==1.4.46
factory-boy==3.1.0
@fdemmer
Copy link

fdemmer commented Aug 20, 2023

Your SQLAlchemy code is incomplete; it is not enough to define a class with some attribute. SQLAlchemy uses declarative mapping. You also need to create a session instance and and not just provide the Session class to SQLAlchemyModelFactory.

I suggest trying the the code example in the factory-boy docs first; you could add a JSON column to that: https://factoryboy.readthedocs.io/en/stable/orms.html#sqlalchemy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants