django tastypie在创建时使用反向关系

时间:2012-09-11 02:10:30

标签: python django rest tastypie

我将以下“付款”字段添加为CheckResource的关系。

class CheckResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user', full=True)
    venue = fields.ForeignKey(VenueResource, 'venue', full=False)
    payments = fields.ToManyField('payments.api.PaymentResource',
        attribute=lambda bundle: Payment.objects.filter(check=bundle.obj),
        related_name=check,
        full=True,
        null=True,
        blank=True
    )

list / get上的一切都很棒,但是当我尝试创建时,我收到以下错误:

{"error_message": "getattr(): attribute name must be string", "traceback": "Traceback (most recent call last):\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n response = callback(request, *args, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n return self.dispatch('list', request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, in dispatch\n response = method(request, **kwargs)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1165, in post_list\n updated_bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1784, in obj_create\n self.save_m2m(m2m_bundle)\n\n File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 1942, in save_m2m\n related_mngr = getattr(bundle.obj, field_object.attribute)\n\nTypeError: getattr(): attribute name must be string\n"}

有任何线索吗?

谢谢! 标记

已更新:我的PaymentResource如下所示:

class PaymentResource(ModelResource):
    from checks.api import CheckResource
    venue = fields.ForeignKey(VenueResource, 'venue', full=False)
    check = fields.ToOneField(CheckResource, 'check', full=False)
    user = fields.ForeignKey(UserResource, 'user', full=False)

1 个答案:

答案 0 :(得分:2)

您遗失的是related_name定义中的ToManyField

Source in the documentation