2011-12-04 10 views
0

Python Elixirで1対多の関係を持つレコードを挿入するにはどうすればよいですか?以下のコードを参照してください。Python Elixir OneToManyとManyToOneの実装:On OneToMany関係で新しいレコードを挿入しますか?

from elixir import *  

class Product(Entity): 
    using_options(shortnames=True) 
    name = Field(Unicode) 
    category = ManyToOne('Category') 
    brand = ManyToOne('Brand') 
    barcode = Field(String) 
    cost = Field(Float) 
    price = Field(Float) 
    order_quantity = Field(Float) 
    unit = Field(Unicode) 



class Category(Entity): 
    using_options(shortnames=True) 
    name = Field(Unicode) 
    product = OneToMany('Product') 

def main(): 
    metadata.bind = 'sqlite:///pypos.sqlite' 
    metadata.bind.echo = False 
    setup_all() 
    create_all() 

    Brand(name='Asrock') 
    Brand(name='Asus') 
    Category(name='Motherboard') 
    Category(name='Processor')  
    session.commit() 

    p = Product(name='N98', cost=2100.50, price=2500.50, order_quantity=5, unit='unit') 

    ''' 
    How do you add a Category and a Brand on the Product table? 
    Is there a lookup for this? 
    ''' 
    #Is there an alternative to this two instruction? 
    p.category = Category(name='Motherboard') 
    p.brand = Brand(name='Asrock') 

    session.commit() 

if__name__=='__main__': main() 

答えて

0

ただ考え出しました。その...

asrock = Brand(name='Asrock') 
asus = Brand(name='Asus') 
mobo = Category(name='Motherboard') 
proc = Category(name='Processor')  
session.commit() 

p1 = Product(name='N98', cost=2100.50, price=2500.50, order_quantity=5, unit='unit',  
    category=mobo, brand=asrock) 

p2 = Product(name='M-N98', cost=2300.50, price=2500.50, order_quantity=5, unit='unit',  
    category=mobo, brand=asus) 

session.commit() 
関連する問題