Tastypie使用自定义detail_uri_name,不匹配的类型错误

时间:2016-07-30 02:08:36

标签: python django model tastypie

我正在尝试覆盖get_bundle_detail_data

class MyResourse(ModelResource):
     foo = fields.CharField( attribute = 'modelA__variableOnModelA' )
     def get_bundle_detail_data(self, bundle):
         return bundle.obj.foo
     class Meta:
         resource_name='resource'

使用代码行foo = fields.CharField( attribute = 'modelA__variableOnModelA' ),我将资源foo上的变量MyResource设置为名为modelA的{​​{1}}上的变量。这很有效。

但我想让variableOnModelA成为variableOnModelA的标识符,这样我就可以MyResource获取详细/api/v1/resource/bar/变量MyResource设置为foo

我遇到的问题是错误:bar这个错误说的是什么?

终极问题:如何将Invalid resource lookup data provided (mismatched type).用作foo

修改 型号:

detail_uri_name

的url:

class AgoraUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='agora_user')
    class Meta:
        db_table = 'agora_users'

实际资源:

full_api = Api(api_name='full')
full_api.register(AgoraUserResourse())
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(full_api.urls)),
    url(r'^', include(min_api.urls)),
    url(r'^search/', include('haystack.urls')),
    url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'),
]

1 个答案:

答案 0 :(得分:1)

您似乎需要覆盖资源的detail_uri_kwargs

我结束了这样的事情:

from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.bundle import Bundle

from .models import AgoraUser


class AgoraUserResourse(ModelResource):
    username = fields.CharField(attribute='user__username')
    class Meta:
        resource_name='user'
        detail_uri_name = 'user__username'
        queryset = AgoraUser.objects.all()
        allowed_methods = ['get', 'put', 'post']
        # authentication = AgoraAuthentication()
        # authorization = AgoraAuthorization()

    def detail_uri_kwargs(self, bundle_or_obj):
        if isinstance(bundle_or_obj, Bundle):
            bundle_or_obj = bundle_or_obj.obj

        return {
            'user__username': bundle_or_obj.user.username
        }

    def get_bundle_detail_data(self, bundle):
        return bundle.obj.username