Flask-Admin多对多字段显示 [英] Flask-Admin Many-to-Many field display

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

问题描述

我开发一个使用Flask的应用程序。我使用Postgres db(psycop2),SQLAlchemy和Flask-Admin作为管理界面。我遇到了一个问题,找不到解决方案。我有文章和标签表之间的多对多的关系很清楚。在Flask-Admin界面中,当我尝试添加一个标签给articel(或者反之亦然)时,它可以正常工作。但它显示很糟糕,不可能选择正确的标签,因为它显示为一个对象:



这是对的,因为它是我的模型类的一个实例。但是,我怎样才能在这里显示来自该模型的单个字段的值?我真的不知道该怎么做。管理界面中是否有这种表单域的参数?我什么都找不到

感谢您的帮助!

解决方案

您需要在模型上定义 __ unicode __ 方法。在一个能够遵循我自己的命名约定的应用程序中,我可以将以下内容放在基类中,以适用于所有模型: class MyModel(db.Model):
基类提供了__repr__,以便每个模型都有短的类型。
__abstract__ = True

def __unicode __(self):
#attrs = db.class_mapper(self .__ class __)。column_attrs
attrs = db.class_mapper(self .__ class __)。attrs#show also relationships
if 'name'attrs:
return self.name
elif'code'attrs:
return self.code
else:
return<%s( %S)>中(self.__ class __.__ name__,
','.join('%s =%r'%(k.key,getattr(self,k.key))
for sort(attrs )



I develop an application using Flask. I use Postgres db (psycop2), SQLAlchemy and Flask-Admin for admin interface. And I got a problem and can't find a solution. I have many-to-many relationship between articles and tags tables it's clear. In the Flask-Admin interface when I try to add a tag to articel (or vise versa) it works fine. But it displays awfully and it impossible to choose correct tag because it displays like an object:

And that is right because it is an instance of my model class. But how can I display here only a value of single field from that model? I really don't know how to do that. Is there any parameter for such kind of "form field" in the admin interface? I can find nothing. I hope that sombody know the solution.

Thanks for your help!

解决方案

You need to define __unicode__ method on your models. In an application where I am able to follow my own naming conventions, I might put the following in the base class for all my models and override where appropriate:

class MyModel(db.Model):
    """ Base class provides the __repr__ so that each model has short type. """
    __abstract__ = True

    def __unicode__(self):
        # attrs = db.class_mapper(self.__class__).column_attrs
        attrs = db.class_mapper(self.__class__).attrs # show also relationships
        if 'name' in attrs:
            return self.name
        elif 'code' in attrs:
            return self.code
        else:
            return "<%s(%s)>" % (self.__class__.__name__,
                ', '.join('%s=%r' % (k.key, getattr(self, k.key))
                    for k in sorted(attrs)
                    )
                )

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

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