0

I'm trying to access the id column of a ForeignKeyField to my UserAccount table through my Like table with various queries such as: if models.Like.select().where(models.Like.user.id==current_user.id,models.Like.post.id==post_id).exists():

I've been trying to access the column id on User and Post. I've achieved this before in a Jinja template by looping through each row and accesing the foreign key through model.Table.foreignkeyfield.foreignkeycolumn like below:

{% for post in posts %}
    {{post.user.username}}
{% endfor %}

(user is a ForeignKeyField, username a column in the User table)

My question is: Is there a way for me to access a foreign key column without looping through the entire table???

'Like' Model

class Like(Model):
    post = ForeignKeyField(rel_model=Post, related_name='Like')
    user = ForeignKeyField(rel_model=UserAccount, related_name='Like')

    class Meta:
        database = db

Much appreciated - Tom

TomHill
  • 614
  • 1
  • 10
  • 26

1 Answers1

1

You don't need to use the id column, peewee should be able to figure it out in the query:

(Like
 .select()
 .where(
     (Like.user==current_user) &
     (Like.post == post_id)).exists():
coleifer
  • 24,887
  • 6
  • 60
  • 75
  • Cool - just out of interest, say I wanted to select a different column through this approach (like the username column of the UserAccount table, how would I achieve that?) – TomHill Dec 19 '15 at 04:36