使用功能count()选择多对多

时间:2018-12-18 13:15:44

标签: flask flask-sqlalchemy

我有很多对很多的关系,我尝试在subs表中找到对请求数最少的User,但我不知道该怎么做。

请您说明我该怎么做

我的模型是:

    subs = db.Table('subs',
                db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
                db.Column('request_id', db.Integer, db.ForeignKey('request.id'))
                )

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))
    role = db.Column(db.String(120))
    password_hash = db.Column(db.String(120))
    requests = db.relationship('Request', secondary=subs,
                               backref=db.backref('users', lazy='dynamic'))
    post = db.relationship('Posts', backref = 'user', lazy = 'dynamic')
    request = db.relationship('Request', backref='user', lazy = 'dynamic')
    is_active = db.Column(db.String(120))


class Request(db.Model):

    __tablename__ = 'request'

    id = db.Column(db.Integer, primary_key=True)
    org = db.Column(db.String(120))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    cost = db.Column(db.Integer)
    created = db.Column(db.DateTime, default= datetime.utcnow)
    cost_time = db.Column(db.Integer)
    update_time = db.Column(db.DateTime, default = datetime.utcnow())
    diff_time = db.Column(db.DateTime)
    feedback = db.Column(db.Text, default=update_time)
    comment = db.relationship('Posts', backref = 'request', lazy='dynamic')
    rate_idea = db.Column(db.Integer)
    new = db.Column(db.Text)
    cost_buyer = db.relationship('Costs', backref = 'request', lazy='dynamic')
    status = db.Column(db.String(120), db.ForeignKey('status.id'))

例如:

User1.requests = [Request_1, 'Request_2, Request_3]
User2.requests = [Request_2, Request_3]

当有人提出新请求时,我首先要弄清哪个用户对所有用户的请求都最少,然后将此请求交给他。

New_request = Request(org = 'TEST')

在这种情况下,User2必须将此New_request添加到自己的User.requests中,以便最终结果必须为

User1.requests = [Request_1, 'Request_2, Request_3]

User2.requests = [Request_2, Request_3, New_request]

我想查询类似的东西,但是我不知道并且我想知道的正确和简单的解决方案是什么?

db.query.filter(min(len(User.requests))

1 个答案:

答案 0 :(得分:0)

类似的事情应该起作用。但我建议您检查docs

10.1.1.1:1521/DB2