lustdante
lustdante

Reputation: 493

Sqlalchemy - Foreign Value

I'm looking for a way to do the following.

class Foo(db.Model):
    __tablename__ = 'foos_foo'
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    # Not an entity in the table but
    # whenever foo.author_name is called,
    # it selects the value from User table
    author_name = author.name

The reason why I'm looking for a way to do is this:

class Foo(db.Model, Serializable):

I made a Serializable mixin so that foo.serialize would simply return row values in json.

I wish author.name to be part of this serialization. Of course, there are countless other ways to get author's name and insert it inside the serialized output, but for the benefit of clean code, I wish to find a way to include foreign value in the model.

I use the misnomer 'foreign key' because I have no idea what the most appropriate keyword is.

Thank you in advance.

Upvotes: 0

Views: 498

Answers (2)

lustdante
lustdante

Reputation: 493

I ended up with using Marshmallow for object serialization.

http://marshmallow.readthedocs.org/en/latest/index.html

These are the implementations.

model.py

class User(db.Model):
    name = db.Column()

class UserSerializer(Serializer):
    class Meta:
        fields = ('id', 'name')

class FooSerializer(Serializer):
    author_name = fields.Nested('UserSerializer')

    class Meta:
        fields = ('id', 'author_name')

view.py

foos = Foo.query.all()
dict = FooSerializer(foos, many=True).data

Upvotes: 1

Victor Shelepen
Victor Shelepen

Reputation: 2256

Objects are not serialize able. I think you need implement a method that convert to JSON. json.dumps works well with dicts. So you can also look at. http://www.marcstober.com/blog/2007/07/07/serializing-arbitrary-python-objects-to-json-using-dict/

You can implement your own method to_json also.

Upvotes: 0

Related Questions