没有模型的Django REST框架

phic 发布于 4 天前 django 最后更新 4 天前 1 浏览

我想使用Django REST框架来创建一个API来调用不同的方法。我阅读了[django-rest-framework] [1]的指南来处理这个框架,但我仍然有一些问题。 我没有模型,我从外部数据库获取数据。我想先尝试一些简单的事情:

  • 获取项目的所有列表
  • 从一个项目获取数据
为此,我创建了一个新的应用程序,包含在设置文件和我的view.py中,包括第一个案例
def connect_database():
  db = MySQLdb.connect(host='...', port=, user='...', passwd='...', db='...')
  try:
    cursor = db.cursor()
    cursor.execute('SELECT * FROM proj_cpus')
    columns = [column[0] for column in cursor.description]
    # all_rows = cursor.fetchall()
    all_rows = []
    for row in iter_row(cursor):
      all_rows.append(dict(zip(columns, row)))
  finally:
    db.close()
  return all_rows
def iter_row(cursor, size= 1000):
  while True:
    results = cursor.fetchmany(size)
    if not results:
      break
    for item_result in results:
      yield item_result
class cpuProjectsViewSet(viewsets.ViewSet):
  serializer_class = serializers.cpuProjectsSerializer
def list(self, request):
    all_rows = connect_database()
    name_project = []  
    for item_row in all_rows:
      name_project.append(item_row['project'])
    name_project = list(sorted(set(name_project)))
    serializer = serializers.cpuProjectsSerializer(instance=name_project, many=False)
    return Response(serializer.data)
我的序列化文件我有这个
class cpuProjectsSerializer(serializers.Serializer):
  project = serializers.CharField(max_length=256)
def update(self, instance, validated_data):
    instance.project = validated_data.get('project', instance.project)
    return instance
现在当我执行这个http://127.0.0.1:8000/hpcAPI时 我得到这个错误
Got AttributeError when attempting to get a value for field `project` on serializer `cpuProjectsSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance.
Original exception text was: 'list' object has no attribute 'project'.
我在谷歌寻找,我改变这一点 serializers.cpuProjectsSerializer(instance=name_project, many=False) for
serializers.cpuProjectsListSerializer(instance=name_project, many=False)
但我得到同样的错误! 任何想法! 非常感谢
已邀请:

liste

赞同来自:

来自docs here。您不必拥有创建Serializer类的模型。您可以定义一些序列化器字段然后使用它们。您不应导入CPUProjectsViewSet并在下面定义它

from mysite.hpcAPI.serializers import CPUProjectsViewSet
class CPUProjectsViewSet(viewsets.ViewSet):
"""
return all project name
"""
    all_rows = connect_database()