【问题标题】:Tastypie using custom detail_uri_name, mismatched type errorTastypie 使用自定义 detail_uri_name,类型不匹配错误
【发布时间】:2016-07-30 02:08:36
【问题描述】:

我正在尝试覆盖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

我遇到的问题是错误:Invalid resource lookup data provided (mismatched type).这个错误是什么意思?

终极问题:如何将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

【问题讨论】:

  • 你能粘贴你的模型和 URL 配置吗?

标签: python django model tastypie


【解决方案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

【讨论】:

  • 这么简单!你为我节省了很多时间。
猜你喜欢
  • 2020-10-02
  • 1970-01-01
  • 2012-09-02
  • 2020-06-27
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多