Вопрос

I have a small app which I have rendering via flask with flask-sqlalchemy:

I have a table setup such that:

Table A

Table B with a foreign key to Table A

Table C and D with a foreign key to Table B

Table A has many children B and table B has many children C and D

Table can be found here: http://pastebin.com/xYLqj9vw

I can successfully query and get objects from A using a query like:

@app.route('/<video>/')
def show_specific_video(video):
    video = Video.query.filter_by(id=video).first_or_404()
    return render_template('video.html', video=video)

and in view:

{% for source in video.files %}
    blah...
{% endfor %}

However if I try to render (using {{ }}) the foreign key in sources (source.video_codec etc) all I get back is the foreign key reference (e.g. 1 for the id of the video_file it references). I dont know how to get the object object the nested foreign key references. How can I go about this?

If I query each C and D individually how do I then map them up to the 'parent' object?

Это было полезно?

Решение

In your VideoFile model you have defined:

video_codec = db.Column(db.Integer, db.ForeignKey(VideoCodec.id))

so say you have some video file:

source = VideoFile.query.get(1)

and you do this

source.video_codec

you are actually referencing the foreign key you set on your VideoFile model, NOT the relationship.

In your VideoCodec model, you have defined a relationship as thus:

videos = db.relationship('VideoFile', backref='Video Codec')

Here you have defined your backref with spaces. I tested it and it is valid. This is setting the attribute 'Video Codec' on the VideoFile model.. You cannot access this with attribute access, ie:
source.Video Codec will confused the interpreter where it will look for source.Video and wonder what variable Codec points to. To get what you are looking for do one of the following:

getattr(source, 'Video Codec')

or change the name of your relationships to have no spaces

videos = db.relationship('VideoFile', backref='Video_Codec')

now source.video_codec will give you the foreign key, and source.Video_Codec will give you the actual relationship.

I also suggest that you rename VideoFile.video_codec to VideoFile.video_codec_id to avoid confusing yourself. If you do, don't forget to change any references to it as well.

Please read the sqlalchemy relationship configuration in more detail to get an idea of best practices.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top