在Flask-Admin中显示一对多关系的第一个元素 [英] Display first element of a one-to-many relationship in Flask-Admin

查看:717
本文介绍了在Flask-Admin中显示一对多关系的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flask-Admin创建一个管理员屏幕,但是我遇到了一个障碍。假设我有两个如下所示的类:

pre $ class $ (db.teger,primary_key = True,unique = True)
part_data = db.relationship(PartHistory,backref =part)
name = db.Column(db.String(255) )

class PartHistory(db.Model):
id = db.Column(db.Integer,primary_key = True,unique = True)
part_id = db.Column(db .Integer,db.ForeignKey('part.id'))
date_checked = db.Column(db.Date)



零件在PartHistory上具有一对多的关系。我想创建一个视图,在一列中显示零件名称,在另一列中显示第一个date_checked。我尝试了这样的事情:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $>

但是这似乎不起作用。这也似乎是我正在做这个错误的方式。任何提示将不胜感激。

解决方案

一种方法是使用 column-property 来定义一个计算列将填充您需要的字段。下面我使用了一个 min 的值,但是你可以构造任意的查询来获得第一个ID(最好的方法来实现,这将是后端特定的):

  class Part(db.Model):
#...
date_checked = db.column_property(
db .select([db.func.min(PartHistory.date_checked)])。\
where(PartHistory.part_id == id).\
correlate_except(PartHistory)

请注意,您可能无法按此列排序。


I'm currently using Flask-Admin to create an admin screen but I'm running into a roadblock. Suppose I have two classes that look like this:

class Part(db.Model):
  id = db.Column(db.Integer, primary_key=True, unique=True)
  part_data = db.relationship("PartHistory", backref="part")
  name = db.Column(db.String(255))

class PartHistory(db.Model):
  id = db.Column(db.Integer, primary_key=True, unique=True)
  part_id = db.Column(db.Integer, db.ForeignKey('part.id'))
  date_checked = db.Column(db.Date)

Part has a one-to-many relationship on PartHistory. I'd like to create a view that shows the Part name in one column and the first date_checked in the other column. I tried something like this:

column_list = ("name", "part_data[0].date_checked")

But that doesn't seem to work. It also seems like I'm going about this the wrong way. Any tips would be appreciated.

解决方案

One way would be to use column-property to define a computed column which would be populated with the field you need. Below I used a min value, but you can construct arbitrary query to get the first by ID (best way to achieve that would be backend-specific):

class Part(db.Model):
  # ...
  date_checked = db.column_property(
        db.select([db.func.min(PartHistory.date_checked)]).\
            where(PartHistory.part_id==id).\
            correlate_except(PartHistory)
    )

Note that you might not be able to sort by this column though.

这篇关于在Flask-Admin中显示一对多关系的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆