Python Elixir OneToMany和ManyToOne实现:On使用OneToMany关系插入新记录?

时间:2011-12-04 04:52:32

标签: python sqlalchemy cpython python-elixir

如何在Python Elixir中插入具有一对多关系的记录?请参阅下面的代码。

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()   

1 个答案:

答案 0 :(得分: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()
相关问题