【问题标题】:django rest framework save(using='database') not workingdjango rest框架保存(使用='数据库')不起作用
【发布时间】:2014-09-07 00:41:19
【问题描述】:

我有以下看法——

class DeployResourceFilterView(generics.ListAPIView):
    serializer_class = ResourceSerializer

    def get(self, request, format=None):
        resname = self.request.GET.get('name')
        queryset = Resmst.objects.using('Admiral').filter(resmst_name=resname)
        serializer = ResourceSerializer(queryset, many=True)
        if queryset:
            return Response(serializer.data)
        else:
            raise Http404

    def post(self, request, format=None):
        serializer = ResourceSerializer(data=request.DATA, many=True)
        if serializer.is_valid():
            serializer.save(using='Admiral')
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

GET 工作正常,正在从“海军上将”数据库中提取数据,但是一旦我从网页上发布帖子,它就会返回一个错误,即该表不存在,因为它正在尝试保存到“默认”数据库。我不确定为什么要这样做,因为我明确地保存到特定的数据库中。这是回溯 -

这里我要注意的是 sqlite3 数据库是默认数据库。 “海军上将”数据库是一个 sql server 数据库。因此我知道 using='Admiral' 不起作用。

Traceback:
File "D:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "D:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  400.             response = self.handle_exception(exc)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  397.             response = handler(request, *args, **kwargs)
File "D:\Tidal\API\views.py" in post
  311.         if serializer.is_valid():
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in is_valid
  553.         return not self.errors
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in errors
  535.                         ret.append(self.from_native(item, None))
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in from_native
  996.         instance = super(ModelSerializer, self).from_native(data, files)
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in from_native
  368.             attrs = self.restore_fields(data, files)
File "D:\Python27\lib\site-packages\rest_framework\serializers.py" in restore_fields
  283.                 field.field_from_native(data, files, field_name, reverted_data)
File "D:\Python27\lib\site-packages\rest_framework\relations.py" in field_from_native
  189.             into[(self.source or field_name)] = self.from_native(value)
File "D:\Python27\lib\site-packages\rest_framework\relations.py" in from_native
  228.             return self.queryset.get(pk=data)
File "D:\Python27\lib\site-packages\django\db\models\manager.py" in get
  151.         return self.get_queryset().get(*args, **kwargs)
File "D:\Python27\lib\site-packages\django\db\models\query.py" in get
  304.         num = len(clone)
File "D:\Python27\lib\site-packages\django\db\models\query.py" in __len__
  77.         self._fetch_all()
File "D:\Python27\lib\site-packages\django\db\models\query.py" in _fetch_all
  857.             self._result_cache = list(self.iterator())
File "D:\Python27\lib\site-packages\django\db\models\query.py" in iterator
  220.         for row in compiler.results_iter():
File "D:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
  713.         for rows in self.execute_sql(MULTI):
File "D:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  786.         cursor.execute(sql, params)
File "D:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  69.             return super(CursorDebugWrapper, self).execute(sql, params)
File "D:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  53.                 return self.cursor.execute(sql, params)
File "D:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  99.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "D:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  53.                 return self.cursor.execute(sql, params)
File "D:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  451.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /deploy/resource/
Exception Value: no such table: owner

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    我不得不通过创建路由器来解决这个问题。我制作了一个引用这个“海军上将”数据库的特定路由器,然后将其分配给应用程序“API”。

    settings.py

    DATABASE_ROUTERS = [ 'routers.DefaultRouter', 'routers.AdmiralRouter', 'routers.TIDALRouter' ]
    

    路由器.py

    class TIDALRouter(object):
        """
        A router to control all database operations on models in the
        auth application.
        """
        def db_for_read(self, model, **hints):
            """
            Attempts to read auth models go to auth_db.
            """
            if model._meta.app_label == 'API':
                return 'Admiral'
            return None
    
        def db_for_write(self, model, **hints):
            """
            Attempts to write auth models go to Admiral.
            """
            if model._meta.app_label == 'API':
                return 'Admiral'
            return None
    
        def allow_relation(self, obj1, obj2, **hints):
            """
            Allow relations if a model in the auth app is involved.
            """
            if obj1._meta.app_label == 'API' or \
               obj2._meta.app_label == 'API':
               return True
            return None
    
        def allow_migrate(self, db, model):
            """
            Make sure the auth app only appears in the 'Admiral'
            database.
            """
            if db == 'Admiral':
                return model._meta.app_label == 'API'
            elif model._meta.app_label == 'API':
                return False
            return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2020-10-30
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多