In django-tastypie, can choices be displayed in schema?

拜拜、爱过 提交于 2019-12-04 16:22:06

You can add the choices to the schema by overriding the method in your resource. If you would want to add the choices to any field (maybe to use with many resources), you could create the method as follows:

def build_schema(self):
    base_schema = super(SomeModelResource, self).build_schema()
    for f in self._meta.object_class._meta.fields:
        if f.name in base_schema['fields'] and f.choices:
            base_schema['fields'][f.name].update({
                'choices': f.choices,
            })
    return base_schema

I haven't tested the above code but I hope you get the idea. Note that the object_class will be set only if you use the tastypie's ModelResource as it is being get from the provided queryset.

A simpler solution is to hack the choices information into your help_text blurb.

In our example we were able to do:

source = models.CharField(
    help_text="the source of the document, one of: %s" % ', '.join(['%s (%s)' % (t[0], t[1]) for t in DOCUMENT_SOURCES]),
    choices=DOCUMENT_SOURCES,
)

Easy peasy, automatically stays up to date, and is pretty much side-effect free.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!