无法通过django-tastypie保存带外键的模型

2 投票
1 回答
929 浏览
提问于 2025-04-17 16:14

我正在尝试使用POST请求来保存一个模型,这个模型有外键。直到我给相关模型设置了“添加”和“修改”的权限,否则它会返回401未授权的错误。

简单的例子:

class AnotherModel(models.Model):
    field = models.TextField()

class MyModel(models.Model):
    foreign_key = models.ForeignKey(AnotherModel)

resources.py

class AnoterResource(ModelResource):
    class Meta:
        queryset = AnoterModel.objects.all()
        resource_name = 'another'
        authorization = DjangoAuthorization()
        authentication = ApiKeyAuthentication()



class MyModelResource(ModelResource):
    foreign = fields.ToOneField(AnoterResource, 'foreign_key')

    class Meta:
       queryset = MyModel.objects.all()
       authorization = DjangoAuthorization()
       authentication = ApiKeyAuthentication()
       allowed_methods = ['get', 'post', 'patch', 'put']

所以,我是否需要为AnotherModel也允许“添加”和“修改”的权限,才能保存MyModelResource,还是我哪里搞错了?

1 个回答

1

首先,你需要检查一下是否已经给用户授予了正确的权限。想了解更多细节,可以参考这个链接

另外,以下的设置对我来说是有效的。所以我的 models.py 文件大致是这样的:

class AnotherModel(models.Model):
    id = models.Integerfield()
    another_field = models.TextField()

class MyModel(models.Model):
    foreign_key = models.ForeignKey(AnotherModel)
    mymodel_field = models.TextField()

resource.py 文件是这样的:

class AnotherResource(ModelResource):       
    class Meta:
        queryset = AnotherModel.objects.all()
        resource_name = 'another'
        authorization = Authorization()

class MyModelResource(ModelResource):
    another = fields.ToOneField(AnotherResource, 'another', full=True)   
    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'myresource'
        authorization = Authorization()

现在,如果我想通过 POST 方法在模型上保存一些新数据,我可以发送以下的 CURL 请求。

curl --dump-header - -H "Content-Type: application/json" -X POST --data { "mymodel_field" : "Some text value": "another" : { "id" : 1243 } }' http://localhost/api/v1/myresource/

希望这些信息能帮助你解决问题。:)

撰写回答