2

我正在尝试使用具有外键的 POST 保存模型。在我为相关模型设置“添加”、“修改”权限之前,它返回 401 未经授权。简单示例:models.py

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

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

资源.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 或者我是否在某个地方弄错了?

4

1 回答 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/

希望这可以帮助您解决问题。:)

于 2013-02-23T17:52:38.663 回答