Faculty of Engineering and Mathematical Sciences 
Not logged in (login)

help3403


This forum is provided to promote discussion amongst students enrolled in Agile Web Development (CITS3403).
 
Options:
RSS cloud
Jump to:

Cascade relations with only objects

2 of 419 articles shown, currently no other people reading this forum.
photo
From: Nicholas T.
Date: Fri 8th May 2020, 1:41pm
Actions: 
        Login-to-reply

 

Hi there,

I was looking for a while and I'm having trouble seeing how this is possible and just 
put a hacky for loop in instead. Say I have 3 models

Quiz:
  questions = db.relationship('Question', backref='quiz', lazy='dynamic')

Question:
  user_answers = db.relationship('UserAnswer', back_populates="answered_question")

UserAnswer:
  user_id = db.Column(db.Integer, ForeignKey('user.id'))
  timestamp = db.Column(db.DateTime, default = datetime.utcnow)
  answered_question = db.relationship('Question', back_populates="user_answers")

Is there a way I can do this without query using only objects?
Like:
userAnswers = quiz.questions.user_answers.filter_by(user_id=current_user)

Do I have to make a join?

Thanks

Cascade relations with only objects

photo
From: Timothy F.
Date: Sat 9th May 2020, 1:40pm
Actions: 
        Login-to-reply

 

Looks like you could define a relation between user and answer that fills that 
criteria.

However, if you you want to select a set of user answers that correspond to certain 
types of quizzes etc then you should use a query with joins. The relationship 
attributes are just shorthands for simople foriegn key lookups. Any complex query that 
depends on mulitple columns in multiple tables should probably be formulated as a 
query.  

An alternative approach (which is effectively the same as a for loopl but more 
pythonic) would be to use quiz.question.user_answers in a list comprehension.

"Nicholas Turner" <21*1*7*[email protected]*u*e*t*u*a*e*u*a*> wrote:

> Hi there,
> 
> I was looking for a while and I'm having trouble seeing how this is possible and just 
> put a hacky for loop in instead. Say I have 3 models
> 
> Quiz:
>   questions = db.relationship('Question', backref='quiz', lazy='dynamic')
> 
> Question:
>   user_answers = db.relationship('UserAnswer', back_populates="answered_question")
> 
> UserAnswer:
>   user_id = db.Column(db.Integer, ForeignKey('user.id'))
>   timestamp = db.Column(db.DateTime, default = datetime.utcnow)
>   answered_question = db.relationship('Question', back_populates="user_answers")
> 
> Is there a way I can do this without query using only objects?
> Like:
> userAnswers = quiz.questions.user_answers.filter_by(user_id=current_user)
> 
> Do I have to make a join?
> 
> Thanks
This Page


Program written by: [email protected]
Feedback welcome
Last modified: 11:27am Sep 21 2020