我正在使用cassandra数据库和django,我想使用Django-rest-frame工作的Serializers来序列化数据。
import uuid
from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model
class Users(Model):
read_repair_chance = 0.05 # optional - defaults to 0.1
uid = columns.UUID(primary_key=True, default=uuid.uuid4)
age = columns.Integer(index=True)
phno = columns.Text(required=True)
uname = columns.Text(required=True)
class Meta:
verbose_name_plural = "user_details"
from rest_framework import serializers
from user_details.models import Users
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ('uid','uname','age','phno')
from user_details.models import Users
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from user_details.serializers import UserSerializer
class UserList(APIView):
def get(self, request , format = None):
users = Users.objects.all()
serializer = UserSerializer(users,many = True)
return Response(serializer.data)
AttributeError at /show_details/
type object 'Users' has no attribute '_meta'
Request Method: GET
Request URL: http://127.0.0.1:8000/show_details/
Django Version: 1.8.5
Exception Type: AttributeError
Exception Value:
type object 'Users' has no attribute '_meta'
我应该做什么更改以序列化json格式显示数据。我已经尝试了类似的带有MySQL数据的serializer.py文件来显示它,因为它工作正常。我所理解的是当我打电话给Users.objects.all()
时显示
>>> from user_details.models import Users
>>> Users.objects.all()
<cassandra.cqlengine.query.ModelQuerySet object at 0x045614F0>
>>>
所以如何检索数据并将其序列化。
答案 0 :(得分:0)
我有同样的问题,但是经过以下修改后,它可以正常工作。
serializers.py
而不是使用serializers.ModelSerializer,而要使用serializers.Serializer。
class UserSerializer(serializers.Serializer):
uid = serializers.UUIDField()
age = serializers.IntegerField()
phno = serializers.CharField()
uname = serializers.CharField()
def create(self, validated_data):
return Users.objects.create(validated_data)
def update(self, instance, validated_data):
instance.uid = validated_data.get('uid', instance.uid)
instance.age = validated_data.get('age', instance.age)
instance.phno = validated_data.get('phno', instance.phno)
instance.uname = validated_data.get('uname', instance.uname)
instance.save()
return instance