SQLAlchemy filter on list attribute

2024/9/16 23:12:11

I have the following model defined with Flask-SQLAlchemy:

"""models.py"""from flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()skill_candidate = db.Table('SkillCandidate',db.Column('skill_id', db.String, db.ForeignKey('skill.id')),db.Column('candidate_id', db.Integer, db.ForeignKey('candidate.id')))class Candidate(db.Model):id = db.Column(db.Integer, primary_key=True)skills = db.relationship("Skill", secondary=skill_candidate)class Skill(db.Model):id = db.Column(db.String, primary_key=True)name = db.Column(db.String, nullable=False, unique=True)

What am trying to achieve is the following : I want to return all the candidates who possess skills provided in a list input (even ideally, a list of skill_id)

I tried the following :

def get_skilled_candidates(skill_ids):return Candidate.query.join(skill_candidate).\filter(and_(*[skill_candidate.c.skill_id == skill_id for skill_id in skill_ids])).\all()

The aim was to filter all candidates for every skill and compose it with a and_ statement

It works well if I use a list of 1 item (it returns all candidates that possess the skill) but does not if I add more skills in the input list (even tho I have candidates in base that fit the criteria)

Answer

You could query all candidates with any of the skills in your list and then filter the result with a list comprehension. This may not be as performant as the relational division approach mentioned by @IljaEverilä, but it certainly simplifies the query aspect.

skill_ids = ['id_1', 'id_2']
candidates = session.query(Candidate).\filter(Candidate.skills.any(Skill.id.in_(skill_ids)).\all()candidates = [c for c in candidatesif set(s.id for s in c.skills).issuperset(skill_ids)
]
https://en.xdnf.cn/q/72639.html

Related Q&A

How to convert an InMemoryUploadedFile in django to a fomat for flickr API?

I have a class that uploads a file to Flickr. The file is of type InMemoryUploadedFile.I would like to know how to convert or pass the data in the InMemoryUploadedFile file, to a format for flickrs API…

Speed up Metropolis-Hastings algorithm in Python

I have some code that samples a posterior distribution using MCMC, specifically Metropolis Hastings. I use scipy to generate random samples:import numpy as np from scipy import statsdef get_samples(n):…

How to properly use Rules, restrict_xpaths to crawl and parse URLs with scrapy?

I am trying to program a crawl spider to crawl RSS feeds of a website and then parsing the meta tags of the article.The first RSS page is a page that displays the RSS categories. I managed to extract t…

sudo required for easy_install pip in OS X Lion?

Im coming from Snow Leopard at work to a Lion installation at home. I do NOT remember having to:sudo easy_install pipIs that required for Lion? I got errors until I did that, and pip ended up here:[…

CUDNN_STATUS_NOT_INITIALIZED when trying to run TensorFlow

I have installed TensorFlow 1.7 on an Ubuntu 16.04 with Cuda 9.0 and CuDNN 7.0.5 and vanilla Python 2.7 and although they samples for both CUDA and CuDNN run fine, and TensorFlow sees the GPU (so some …

What is the correct way to switch freely between asynchronous tasks?

Suppose I have some tasks running asynchronously. They may be totally independent, but I still want to set points where the tasks will pause so they can run concurrently. What is the correct way to run…

How to write integers to port using PySerial

I am trying to write data to the first serial port, COM1, using PySerial.import serial ser = serial.Serial(0) print (ser.name) ser.baudrate = 56700 ser.write("abcdefg") ser.close()ought to wo…

Pandas sort columns by name

I have the following dataframe, where I would like to sort the columns according to the name. 1 | 13_1 | 13_10| 13_2 | 2 | 3 9 | 31 | 2 | 1 | 3 | 4I am trying to sort the columns in the f…

Series objects are mutable, thus they cannot be hashed error calling to_csv

I have a large Dataframe (5 days with one value per second, several columns) of which Id like to save 2 columns in a csv file with python pandas df.to_csv module.I tried different ways but always get t…

Python client / server question

Im working on a bit of a project in python. I have a client and a server. The server listens for connections and once a connection is received it waits for input from the client. The idea is that the c…