2012-03-09 1 views
0

Я пытаюсь написать мнение/SQLAlchemy запрос, который позволит мне для отображения данных, связанные Thats как ForeignKey, а также, где у меня есть отношения ManyToManySQLAlchemy запросы ForeignKey поле (s)

есть модели ..

#Samples 
class Sample(Base): 
    __tablename__ = 'samples' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode) 

    def __unicode__(self): 
     return self.name 

samples_to_customer = Table('samples_to_customer', Base.metadata, 
    Column('customer_id', Integer, ForeignKey('customer.id')), 
    Column('sample_id', Integer, ForeignKey('samples.id')) 
) 

#Create a cusotmer model to store customer numbers 
class Customer(Base): 
    __tablename__ = 'customer' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode, unique=True) #this will be the variable used to search the existing db 
    customer_samples = relationship('Sample', secondary='samples_to_customer', backref='samples') 
    sales_rep = Column(Integer, ForeignKey('rep.id')) 
    Rep = relationship('Rep') 

    def __unicode__(self): 
     return self.name 

# This model will have its own entry view/page a user logs on and enters notes (according to a customer 
# number) they then get stored/saved onto the Customers account 
class Note(Base): 
    __tablename__ = 'note' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode) 
    pub_date = Column(Date) 
    customer_no = Column(Integer, ForeignKey('customer.id')) 
    customer = relationship('Customer') 

    def __unicode__(self): 
     return self.name 

и взгляды ..

@view_config(route_name='view_customer', renderer='templates/view_customer.jinja2') 
def view_page(request): 
    customer_no = request.matchdict['customer'] 
    cust_slcustm = DBSessionRO.query(Slcustm).filter(Slcustm.customer == customer_no).first() 
    cust_customer = DBSessionRO.query(Custom).filter(Custom.cu_custref== customer_no).first() 

    # Return a 404 if a result isn't found, slcustm and customer share one2one relationship on customer_no 
    if cust_slcustm is None: 
     return HTTPNotFound('No such customer') 

    return dict(cust_slcustm=cust_slcustm, cust_customer=cust_customer) 

Но я не могу показаться, чтобы написать запрос, который будет отображать каждый образец и записку, связанную с номером клиента? Если кто-то может помочь я был бы очень благодарен :)

+1

Это лучше если бы вы могли поставить свой код здесь;) – sacabuche

+2

Что вы пробовали? Что сработало, а что нет? Вы получили сообщение об ошибке? Вы получили неправильные данные? – katrielalex

ответ

0

Что в конечном итоге работает было:

#views.py 
@view_config(route_name='view_customer', renderer='templates/view_customer.jinja2') 
def view_page(request): 
    customer_no = request.matchdict['customer'] 
    cust_slcustm = DBSessionRO.query(Slcustm).filter(Slcustm.customer == customer_no).first() 
    cust_customer = DBSessionRO.query(Custom).filter(Custom.cu_custref== customer_no).first() 
    cust_books = DBSessionRW.query(Customer).filter(Customer.name == customer_no).first() 

    # Return a 404 if a result isn't found, slcustm and customer share one2one relationship on customer_no 
    if cust_slcustm is None: 
     return HTTPNotFound('No such customer') 

    return dict(cust_slcustm=cust_slcustm, cust_customer=cust_customer, cust_books=cust_books) 

Затем создать шаблон:

{% for sample in cust_books.customer_samples %} 
    {{ sample.name }} 
{% endfor %} 
1

Попробуйте

class Note(Base): 
    __tablename__ = 'note' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode) 
    pub_date = Column(Date) 
    customer_no = Column(Integer, ForeignKey('customer.id')) 
    customer = relationship('Customer', backref='notes') 

@view_config(route_name='view_customer', renderer='templates/view_customer.jinja2') 
def view_page(request): 
    customer_no = request.matchdict['customer'] 
    cust = DBSessionRO.query(Customer).filter(Customer.id == customer_no).first() 

    print "Sample :", cust.customer_sample 
    print "Notes :", cust.notes 
+0

Бэкред помог мне с другой борьбой, которую я получил, спасибо! :) – Crooksey