【问题标题】:How to make post data in a three many to many models with flask and sqlalchemy如何使用flask和sqlalchemy在三个多对多模型中发布数据
【发布时间】:2021-07-02 08:19:13
【问题描述】:

我在三个表源类别和关键字之间的多对多关系概念中具有三个模型:

class SourceDevice(db.Model):
    __tablename__ = "source_devices"

    id = db.Column(db.Integer, primary_key=True)
    source_id = db.Column(db.Integer, db.ForeignKey("sources.id"), nullable=False)
    categorie_id = db.Column(db.Integer, db.ForeignKey("categories.id"), nullable=False)
    keyword_id = db.Column(db.Integer, db.ForeignKey("keywords.id"), nullable=False)

    __table_args__ = (db.UniqueConstraint(source_id, categorie_id, keyword_id),)

    sources = db.relationship("Sources", back_populates="source_devices")
    categories = db.relationship("Categories", back_populates="source_devices")
    keywords = db.relationship("Keywords", back_populates="source_devices")

class Sources(db.Model,UserMixin):
    __tablename__ = "sources"
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    source = db.Column(db.String(200), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    #catgeorie_id =  db.Column(db.Integer, db.ForeignKey('categories.id'))
    date_created = db.Column(db.DateTime, default=datetime.utcnow)
    source_devices  = db.relationship('SourceDevice', back_populates='sources')
    #categories = db.relationship('Categories', secondary=categories_sources, lazy='subquery',
    #    backref=db.backref('pages', lazy=True))
    def serialize(self):
        return {'id': self.id,
                'source': self.source,
                'user_id': self.user_id,
                'date_created': self.date_created,
       }

class Categories(db.Model,UserMixin):
    __tablename__ = "categories"
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String(200), nullable=False)
    #source_id = db.Column(db.Integer, db.ForeignKey('sources.id'))
    date_created = db.Column(db.DateTime, default=datetime.utcnow)
    #keyword = db.relationship('Keywords', backref='categorie', lazy='dynamic')
    source_devices  = db.relationship('SourceDevice', back_populates='categories')
    def serialize(self):
        return {'id': self.id,
                'categorie': self.category,
                'date_created': self.date_created,
                 }


class Keywords(db.Model,UserMixin):
    __tablename__ = "keywords"
    
    id = db.Column(db.Integer, primary_key=True)
    keyword = db.Column(db.String(200), nullable=False)
    date_created = db.Column(db.DateTime, default=datetime.utcnow)
    source_devices  = db.relationship('SourceDevice', back_populates='keywords')

    def serialize(self):
        return {'id': self.id,
                'keyword': self.word,
                 'date_created': self.date_created,

                }

我发现此链接很有帮助: Many-to-Many with three tables relating with each other (SqlAlchemy) 据我了解,我必须使用下面的代码来添加基于现有来源和现有类别的 ne 关键字:

categorie = db.session.query(Categories).filter(Categories.category == "Bricolage").first()
source = db.session.query(Sources).filter(Sources.source == "Amazon").first()
keyword = db.session.query(Keywords).filter(Keywords.keyword == "Marteau").first()
assoc = SourceDevice(sources=source, categories=categorie, keywords=keyword)
db.session.add(assoc)
db.session.commit()

但是如何仅基于来源添加类别而无需放置关键字。 如果我在模型中做错了也请纠正我。

谢谢。

【问题讨论】:

  • assoc =SourceDevice(source_id = source.id, categorie_id = categorie.id, keyword_id=keyword.id) ,您需要添加数据库中所需的值而不是整个对象
  • @sahasrara62 我可以在 sources_devices 表中删除所有 id 都不能为空的条件吗?
  • 取决于你想要达到的目标,如果用你的逻辑添加可空的工作那么它很好,否则没有
  • @sahasrara62 它有效。谢谢
  • 在答案中添加解决方案,以供将来参考

标签: python flask sqlalchemy flask-restful


【解决方案1】:

对于一个基于源的三对多概念的解决方案:

categorie = db.session.query(Categories).filter(Categories.category == a given categoy).first()
source = db.session.query(Sources).filter(Sources.source == a given source ).first()

assoc = SourceDevice(sources=source, categories=categorie )
db.session.add(assoc)
db.session.commit()

确保将 SourceDevice 模型的 id_source、id_category 和 id_category 中的至少两个添加为可为空。

【讨论】:

    【解决方案2】:

    你需要根据class字段在你的Source模型类中提供数据。

    assoc =SourceDevice(source_id = source.id, categorie_id = categorie.id, keyword_id=keyword.id)
    

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 2014-05-26
      • 1970-01-01
      • 2014-09-21
      • 2018-01-22
      • 2019-01-09
      • 2020-01-02
      • 2014-10-29
      • 1970-01-01
      相关资源
      最近更新 更多