Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...