Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

Getting <django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50> in model fields instead of actual values

In the code below, I've created an endpoint to create a user in the database.

class ClientViewSet(viewsets.ModelViewSet):
  serializer_class = ClientSerializer
  queryset = Clients.objects.all()

@action(detail=True, methods=["POST"])
def create_client(self, request, pk=None):
    Clients.objects.create(client_id=pk, username=Clients.username, password=Clients.password, first_name=Clients.first_name, last_name=Clients.last_name, address=Clients.address)
    return Response("User Created", status= status.HTTP_200_OK)

This indeed creates an instance in the the model, but each field contains texts similar to "<django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50>" instead of the actual values. I used Postman as a tool, and is how I created this instance, if I just use a 'Post' method on the url ../client/ instead of ../client/pk/create_client/ it returns the correct values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a solution.

assign variables to the body fields of the input data, then substitute it within the 'create':

@action(detail=True, methods=["POST"])
def create_client(self, request, pk=None):
    username = request.data['username']
    password = request.data['password']
    first_name = request.data['first_name']
    last_name = request.data['last_name']
    address = request.data['address']
    Clients.objects.create(client_id=pk, username=username, password=password, first_name=first_name, last_name=last_name, address=address)
    return Response("User Created", status= status.HTTP_200_OK)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...