xbladetm
xbladetm

Reputation: 111

update duplicates data in relationship flask sqlalchemy

I have a Flask-restless API to add and retrieve data from a database. Some of the fields need to be localised for the clients so there is an auxiliary table with the language and string for each field.

class MyClass(Base):
    __tablename__ = 'myclass'
    id = Column(Integer, primary_key = True)   
    translated_field = relationship('TranslatedField')

And the translation table:

class TranslatedField(Base):
    __tablename__ = 'translated_field'

    id = Column(Integer, primary_key = True)
    myclassID = Column(Integer, ForeignKey('myclass.id'))
    language = Column(String(2))
    value = Column(Text)

Inserts through JSON work fine with {...,"translated_field":[{"language":"en", "value": "some value"}],...}

But when i do the same with a PUT request, it sets the myClassID to null in the existing row in the translated_field table and inserts a new row with the modified data rather than updating the existing one.

Obviously this is not ok because it fills the database with garbage. The question is: Can i get it to just modify the existing rows or do i have to "clean" the DB manually in a pre or post processor?

Upvotes: 0

Views: 257

Answers (1)

xbladetm
xbladetm

Reputation: 111

Solved it. It turns out I wasn't passing any values for the primary key (autoincrement id) of the related objects so it didn't know what to update.

request fragment should look like this ...,"translated_field":[{"id":3 "language":"en", "value": "some value"}],...}

Upvotes: 1

Related Questions