简体   繁体   English

Django-tastypie-如何包含选择?

[英]Django-tastypie - how to include choices?

I have a model field like this 我有一个这样的模型场

location_state = models.CharField(max_length=255, null=True, blank=True, choices=STATE_CHOICES)

Its value is returned by tastypie, but for rendering a listbox a list of all available choices is needed. 它的值由tastypie返回,但是要呈现一个列表框,需要所有可用选项的列表。 What's the best way to expose such choices via a resource? 通过资源公开此类选择的最佳方法是什么?

I couldn't find an easy way of getting the choices out for some reason, but this will do the trick. 由于某种原因,我找不到一种简单的选择方法,但这可以解决问题。

YourModel._meta.get_field('location_state').choices

You should note though, _meta is an internal implementation detail, but has been relied upon with a large number of apps and extensions so it should be relatively safe to use. 您应该注意, _meta是内部实现细节,但是已被大量的应用程序和扩展所依赖,因此使用它应该相对安全。

I'd use the built-in schema to inform the client about field options. 我会使用内置模式来通知客户端有关字段选项的信息。 Still, choice options are not included in the schema resource by default. 仍然,默认情况下,模式资源中不包含选择选项。 This thread shows one way how to achieve this. 该线程显示了一种实现此目的的方法。

Edit 2013-03-19 : 编辑2013-03-19

Alternatively you could add your choices to the meta field by using / overriding the alter_list_data_to_serialize method in your ModelResource . 或者,您可以通过使用/覆盖ModelResourcealter_list_data_to_serialize方法来将选择添加到meta字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM