编程语言
首页 > 编程语言> > python – Tastypie使用自定义detail_uri_name,不匹配的类型错误

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

作者:互联网

我试图覆盖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’),我将资源MyResource上的变量foo设置为modelA上名为variableOnModelA的变量.这很有效.

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

我遇到的问题是错误:提供的资源查找数据无效(类型不匹配).这个错误说的是什么?

终极问题:我如何使用foo作为detail_uri_name?

编辑
模型:

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'),
]

实际资源:

class AgoraUserResourse_min(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 get_bundle_detail_data(self, bundle):
        return bundle.obj.username

解决方法:

看起来您需要覆盖您的资源的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

标签:python,django,model,tastypie
来源: https://codeday.me/bug/20190706/1394506.html