2016-06-29 1 views
0

私はto_json関数で2つのフィールドにアクセスする関連オブジェクトを持っています。一つは文字列であり、もう1つはここに小数SQLAlchemy to_json関数をどのようにしてカラムタイプを出力に追加しないのですか?

であることはオブジェクトである:

class DrinkIngredient(db.Model): 
    __tablename__ = 'drink_ingredient' 
    drink_id = db.Column(db.Integer, db.ForeignKey("drink.id"), primary_key=True) 
    ingredient_id = db.Column(db.Integer, db.ForeignKey("ingredient.id"), primary_key=True) 
    units = db.Column(db.Numeric(4, 2)) # Total of 4 digits, 2 after decimal: 00.00 

    ingredient = db.relationship("Ingredient") 

    def __init__(self, ingredient=None, units=None): 
     self.ingredient = ingredient 
     self.units = units 

    def __repr__(self): 
     return '<DrinkIngredient %g units of %r>' % (self.units, self.ingredient) 

    def to_json(self): 
     json_drinkIngredient = { 
      "ingredient": self.ingredient.name, 
      "amount": self.units 
     } 
     return json_drinkIngredient 

Ingredient.name Ingredientと呼ばれる別のテーブル内の文字列です。

私はこの関数を呼び出すとDecimal('...')u'...'が含まれているとどのように私が正しく記載されているタイプせずに、これらのJSONオブジェクトを作るのですか、なぜ私はこの {'amount': Decimal('0.20'), 'ingredient': u'grenadine'}

のような出力が得られます。

また、これは大きな問題ではありませんが、私はむしろ逆の順序でそれらを定義した順序であると思います。なぜ彼らがその順序でないのかわかりません。

答えて

0

jsonモジュールを使用して適切なjsonを出力します。あなたの2番目の質問について

from simplejson import dumps 

def to_json(self): 
    json_drinkIngredient = dumps({ 
     "ingredient": self.ingredient.name, 
     "amount": self.units 
    }) 
    return json_drinkIngredient 

、その理由はPythonの辞書は順不同であるということです。それはOrderedDictを使用し、あなたが鍵を宣言したと秩序を維持し、json.dumpsにそのオブジェクトを渡すことが重要です場合:

from collections import OrderedDict 

d=OrderedDict() 
d['ingredient']=self.ingredient.name 
d['amount']=self.units 
+0

を私は認識して波平このJSONモジュールを存在していました。それはピュータンズ基地の一部ですか? – user8363

+0

うん、標準のpython、電池が付属! – fips

+0

json.dumps()を使用すると 'Decimal( '1.00')がJSONのシリアライザブルではないというエラーが発生しました。 – user8363

関連する問題