Flask-sqlAlchemy les relations des tables ne marchent pas trop bien

Bonjour à tous
J’utilise flask et Flask-sqlAlchemy pour développer une petite api de quiz mais je rencontre un certain problème avec la bdd (j’utilise SQLite)
Pendant la requête,le filtrage par tags ne marche pas

Voici les modèles de tables :

class QuestionTag(db.Model):

__tablename__ = 'question_tags'

id = db.Column(db.Integer, primary_key=True)

question_id = db.Column(db.Integer, db.ForeignKey('question.id'), nullable=False)

tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'), nullable=False)

question = db.relationship('Question', backref=db.backref('question_tags', cascade='all, delete-orphan'))

tag = db.relationship('Tag', backref=db.backref('question_tags', cascade='all, delete-orphan'))

class Question(db.Model):

id = db.Column(db.Integer, primary_key=True)

auteur = db.Column(db.String(100), nullable=False)

difficulty = db.Column(db.String(20), nullable=False)

category = db.Column(db.String(100), nullable=False)

question = db.Column(db.Text, nullable=False)

reponse_correct = db.Column(db.Text, nullable=False)

reponse_incorrect1 = db.Column(db.Text, nullable=False)

reponse_incorrect2 = db.Column(db.Text, nullable=False)

reponse_incorrect3 = db.Column(db.Text, nullable=False)

explication = db.Column(db.Text, nullable=True)

tags = db.relationship('Tag', secondary='question_tags', backref='questions')

statut = db.Column(db.String(50), nullable=False, default='en revision')

date_ajout = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

date_modification = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)



def to_dict(self):

    # Cette méthode permet de convertir l'objet Question en dictionnaire

    return {

        'id': self.id,

        'auteur': self.auteur,

        'difficulty': self.difficulty,

        'category': self.category,

        'question': self.question,

        'tags': [tag.name for tag in self.tags],

        'reponse_correct': self.reponse_correct,

        'reponse_incorrect1': self.reponse_incorrect1,

        'reponse_incorrect2': self.reponse_incorrect2,

        'reponse_incorrect3': self.reponse_incorrect3,

        'explication': self.explication

    }

class Tag(db.Model):

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String(50), nullable=False, unique=True)

#Et ça c’est la route pour la requête GET :

#Recuperer le detail d’une question spécifique

@app.route(‘/api/v1/ressources/questions/specifique’, methods=[‘GET’])

def get_questions():

# Récupération de la clé API de la requête

api_key = request.headers.get('X-API-Key')

# Vérification de la clé API

user = AdminUser.query.filter_by(api_key=api_key).first()

if not user :

    return jsonify({'error': 'Invalid API key'}),400

print(user.username,api_key)

# Mise à jour du compteur d'appels API

user.api_calls_count += 1

db.session.commit()

# Récupération des autres paramètres de la requête

limit = request.args.get('limit', type=int)

params = {

    'categorys': request.args.getlist('category'),

    'difficulty': request.args.get('difficulty'),

    'tags': request.args.getlist('tag'),

}



# Filtrage des questions

query = Question.query

query = filter_questions(query, params)



# Sélection aléatoire des questions

questions = query.all()

if limit:

    questions = random.sample(questions, min(limit, len(questions)))

else:

    return jsonify({

“error”: {

"code": 400,

"message": "Parametre 'limit' Invalide. Doit etre un entier positif.",

"details": {

  "field": "limit",

  "expected": "integer > 0",

  "received": limit

}

}

}),400

# Conversion des objets Question en dictionnaires

questions_dict = [question.to_dict() for question in questions]



return jsonify(questions_dict)

#Ça c’est la fonction pour le filtrage

def filter_questions(query, params):

choix_diff=['facile','moyen','difficile']

category_quiz = ['histoire', 'geographie', 'musique', 'cinema', 'sport', 'science', 'technologie', 'art', 'littérature', 'langues', 'animaux', 'alimentation', 'mythologie', 'politique', 'economie', 'religion', 'santé', 'cuisine', 'celebrites', 'nature']

if params.get('categorys'):

    categorys = [category.lower() for category in params['categorys']]

    if len(categorys) == 1:

        for i in category_quiz:

            if i == categorys[0].lower():

                query = query.filter(Question.category == categorys[0].lower())

                break

    else:

        cat = [i.lower() for i in category_quiz if i.lower() in categorys]

        query = query.filter(Question.category.in_(cat))



if params.get('difficulty'):

    difficulty = params['difficulty'].lower()

    if difficulty in choix_diff:

        query = query.filter(Question.difficulty == difficulty)

    else:

        return jsonify({

            "error": {

                "code": 400,

                "message": "Parametre 'difficulty' Invalide. Doit etre 'Facile' , 'Moyen' ou 'difficile' .",

                "details": {

                    "field": "difficulty",

                    "expected": "['facile', 'moyen', 'difficile']",

                    "received": difficulty

                }

            }

        }), 400



if params.get('tags'):

    tags = params['tags']

    query = query.filter(Question.tags.any(Tag.name.in_(tags)))

    print(Question.tags.any(Tag.name.in_(tags)))



return query        

Je voudrais bien pouvoir résoudre ce problème,
Parceque j’ai déjà passé des semaines sur ça

New contributor

Angelo Ntoto is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật