我有一个系统,我将拥有可由一名或多名教师教授的产品(课程)。这些讲师还可以创建产品,在这种情况下,他们应该可以通过作为其开发人员的产品进行访问。但是,我还希望能够访问所有可用于该产品的讲师。
我不确定如何设置 SQLAlchemy 模型,以便我可以只Product.developer
为Product.instructors
.
模型.py
from app import db
instructors = db.Table('instructors',
db.Column('instructor_id', db.Integer, db.ForeignKey('instructor.id')),
db.Column('product_id', db.Integer, db.ForeignKey('product.id'))
)
class Instructor(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(64))
#courses qualified for etc
class Product(db.Model):
id = db.Column(db.Integer, primary_key = True)
courseName = db.Column(db.String(64))
developer = db.relationship('Instructor', secondary=instructors,
backref=db.backref('developed', lazy='dynamic'))
instructors = db.relationship('Instructor', secondary=instructors,
backref=db.backref('products', lazy='dynamic'))
def __repr__(self):
return '<Category> %r>' % (self.courseName)
视图.py
from flask import render_template, flash, redirect
from app import app, models
@app.route('/product/<courseName>')
def show_product(courseName):
product = models.Product.query.filter_by(courseName=courseName).first_or_404()
return render_template('show-product.html', product=product)
模板:show-product.html
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<br><b>Course Name:</b> {{product.courseName}}
<br><b>Curriculum developer:</b>
{% for developer in product.developer %}
{{developer.name}}
{% endfor %}
<br><b>Lead Instructor:</b>
<br><b>Certified Instructors:</b>
{% for instructor in product.instructors %}
{{instructor.name}}
{% endfor %}
{% endblock %}`enter code here`
这是我正在运行以在数据库中输入值的代码。
#!flask/bin/python
from app import db, models
instruct1 = models.Instructor(name="instructor1")
db.session.add(instruct1)
db.session.commit()
instruct2 = models.Instructor(name="instructor2")
db.session.add(instruct2)
db.session.commit()
dev = models.Instructor(name="developer")
db.session.add(dev)
db.session.commit()
prod = models.Product(courseName = "test")
prod.instructors = [instruct1]
prod.instructors.append(instruct2)
prod.developer = [dev]
print "Instructors:"
for instructor in prod.instructors:
print instructor.name
print "Developer"
for i in prod.developer:
print i.name
db.session.add(prod)
db.session.commit()
这是输出:
Instructors:
instructor1
instructor2
Developer
developer
但是当我查看网页时,我看到:
Course Name: test
Curriculum developer: instructor1 instructor2 developer
Lead Instructor:
Certified Instructors: instructor1 instructor2 developer
更新:谢谢doobeh!我更新了我的代码http://bpaste.net/show/o8PtsY3Kvu8bxKnDEo24/但是当我运行 python 代码时出现错误“在关系'Product.instructors'上创建反向引用'产品'时出错:映射器上存在该名称的属性'映射器|讲师|讲师'