Skip to main content
 首页 » 编程设计

python之Django Rest 模型配置不当 :

2024年11月24日32daizhj

我尝试在查询 API 而不是数据库的地方使用 Django ORM。 我找到了库 Django Rest Models,它与库 dynamic-rest 一起执行此操作。

我的模型叫做 Client,当我运行时:

Client.objects.filter(id=62) 

我收到以下错误:

ImproperlyConfigured: the response does not contains the result for client.   
maybe the resource name does not match the one on the api. please check if  
Client.APIMeta.resource_name_plural is ok had [u'last_name', u'first_name',  
u'agent',...] in result 

谁能帮助我了解如何修复此错误?

附加信息

这是我在客户端的模型

class Client(models.Model): 
    first_name = models.CharField(max_length=50) 
    last_name = models.CharField(max_length=50) 
    agent = models.ForeignKey(Agent, db_column='agent') 
    ..... 
 
 
    class APIMeta: 
        resource_path = 'clients' 
        resource_name = 'client' 
        resource_name_plural = 'clients' 
        pass 

这是我在 API 上的代码

class ClientSerializer(DynamicModelSerializer): 
    agent = DynamicRelationField('AgentSerializer') 
    class Meta: 
        fields = '__all__' 
        model = Client 
        name = 'client' 
 
 
class AgentSerializer(DynamicModelSerializer): 
 
    client = DynamicRelationField('ClientSerializer', many=True) 
 
    class Meta: 
        fields = '__all__' 
        model = Agent 

更新

经过调试,我发现返回的数据没有模型名称作为键。如何以所需格式返回数据?

请您参考如下方法:

django-rest-models 严重依赖于 dynamic-rest 框架。
在尝试使用 django-rest-models 之前阅读 dynamic-rest 的文档很重要。

在这种情况下, View 集继承自 ModelViewSet,而它们本应继承自 DynamicModelViewSet。