简体   繁体   中英

Comparing data from one fetch request with another

I have three postgres tables: users, files, and likes.

The users table has a one to many relationship with the files table.
The files table has a one to many relationship with the likes table.

My application has a feed with two sections: "community" and "likes". The "community" section consists of all the public user files and the "likes" section consists of all the files liked by the user. Upon loading the feed, I fetch the files for both sections and I end up with an array of dictionaries for each section. My queries look like this:

cur.execute('SELECT f.*, u.username from files as f, users as u '
            'where u.id = %i AND f.user_id = %i ORDER BY f.id DESC' %
            (user.id, user.id))

cur.execute('SELECT f.*, u.username from files as f, users as u, likes as l '
            'where l.user_id = %i AND l.file_id = f.id AND f.share = True AND '
            'u.id = f.user_id ORDER BY f.id DESC' % (user.id))

My "community" feed has a like button that changes to "liked" when the file has been liked. Since I have an array for "community" files and an array of "liked" files, what would be the best way to check if the file ID in the "Community" array is also in the "liked" array so I can update the button?

The "community" and "liked" arrays consist of dictionaries like below:

community_files_dict = {'file_id': file[0], 'user_id': file[1], 'title': file[2],
                        'date': date_final, 'shared': file[4], 'username': file[5]}

liked_files_dict = {'file_id': file[0], 'user_id': file[1], 'title': file[2],
                    'date': date_final, 'shared': file[4], 'username': file[5]}

Check for liked in the first query:

cur.execute('''
    select f.*, u.username, l.user_id is not null as liked
    from
        files f
        inner join
        users u on u.id = f.user_id
        left join
        likes l on l.user_id = u.id and f.share = true
    where u.id = %s
    order by f.id desc
''', (user.id,))

Improvements: join syntax, multi line string, passing parameters through the driver in instead of string interpolation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM