Skip to main content
 首页 » 编程设计

python之无法通过 django-tastypie 发布来保存具有外键的模型

2025年05月04日34lexus

我正在尝试使用具有外键的 POST 保存模型。在我为相关模型设置“添加”、“修改”权限之前,它会返回 401 未授权。 简单示例: 模型.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 或我是否在某处弄错了?

请您参考如下方法:

为此,您需要首先检查您是否已向用户授予适当的权限。更多详情请引用this链接。

以下设置也适用于我。所以我的 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/ 

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