How better way to create a function to pass a JSON by serializer in django rest?How to debug in Django, the good way?Creating a JSON response using Django and PythonDjango REST framework: non-model serializerHow can I do a bulk_create in django REST Framework with nested models?How can i correctly pass arguments to classbasedviews testing Django Rest Framework?Python Django rest-framework serializer omitting fieldHow to serialize GenericForeignKey in DRF?Django-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerDjango rest framework add more data when serialize many objectserializer.is_valid() works with integer fields but serializer.save() asks for model instance
Knights and Knaves: What does C say?
Mac disaster! No longer boots - can’t finish my uni stuff
Ĉi tie or ĉi-tie? Why do people sometimes hyphenate ĉi tie?
Why did they use ultrafast diodes in a 50 or 60 Hz bridge?
How important is knowledge of trig identities for use in Calculus
PhD Length: are shorter PhD degrees (from different countries) valued differently in other counter countries where PhD Is a longer process?
Can I bring this power bank on board the aircraft?
Why the first octet of a MAC address always end with a binary 0?
Notation clarity question for a conglomerate of accidentals
How to refresh wired service getRecord manually?
Why is there such a singular place for bird watching?
Why is music is taught by reading sheet music?
Digital Bananas
What did the Federation give the Prophets in exchange for access to the wormhole in DS9?
Rank-one positive decomposition for a entry-wise positive positive definite matrix
Can a passenger predict that an airline or a tour operator is about to go bankrupt?
Found a minor bug, affecting 1% of users. What should QA do?
How to level a picture frame hung on a single nail?
Isn't the detector always measuring, and thus always collapsing the state?
Job interview by video at home and privacy concerns
Is there a way to make an animal companion able to read a language?
Why Vegetable Stock is bitter, but Chicken Stock not?
IEEE 754 square root with Newton-Raphson
Is there a pattern for handling conflicting function parameters?
How better way to create a function to pass a JSON by serializer in django rest?
How to debug in Django, the good way?Creating a JSON response using Django and PythonDjango REST framework: non-model serializerHow can I do a bulk_create in django REST Framework with nested models?How can i correctly pass arguments to classbasedviews testing Django Rest Framework?Python Django rest-framework serializer omitting fieldHow to serialize GenericForeignKey in DRF?Django-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerDjango rest framework add more data when serialize many objectserializer.is_valid() works with integer fields but serializer.save() asks for model instance
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.
For help I wrote a code example below.
Serialzer example:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car
Well. I need to update a car list through the garage serializer. I'm thinking anything like this:
(example view)
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=True, methods=['put'])
def update_car(self, request):
...
serializer = CarSerializer(queryset, many=True)
...
return Response(serializer.data)
Attempt 1:
Searching and reading the doc, I tried this way:
@action(methods=['put'], detail=False)
def update_car(self, request, *args, **kwargs):
if request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CarSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
But I received this error:
non_field_errors:
["Expected a list of items but got type "dict"."]
Attempt 2:
With a @fxgx I tried too:
def update_car(self, request):
serializer = CarSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = dict(list(serializer.validated_data.items()))
queryset = Car.objects.update(**validated_data)
return Response(CarSerializer(queryset, many=True).data)
But I received this error:
"detail": "Not found."
python django django-rest-framework
add a comment
|
I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.
For help I wrote a code example below.
Serialzer example:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car
Well. I need to update a car list through the garage serializer. I'm thinking anything like this:
(example view)
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=True, methods=['put'])
def update_car(self, request):
...
serializer = CarSerializer(queryset, many=True)
...
return Response(serializer.data)
Attempt 1:
Searching and reading the doc, I tried this way:
@action(methods=['put'], detail=False)
def update_car(self, request, *args, **kwargs):
if request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CarSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
But I received this error:
non_field_errors:
["Expected a list of items but got type "dict"."]
Attempt 2:
With a @fxgx I tried too:
def update_car(self, request):
serializer = CarSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = dict(list(serializer.validated_data.items()))
queryset = Car.objects.update(**validated_data)
return Response(CarSerializer(queryset, many=True).data)
But I received this error:
"detail": "Not found."
python django django-rest-framework
add a comment
|
I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.
For help I wrote a code example below.
Serialzer example:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car
Well. I need to update a car list through the garage serializer. I'm thinking anything like this:
(example view)
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=True, methods=['put'])
def update_car(self, request):
...
serializer = CarSerializer(queryset, many=True)
...
return Response(serializer.data)
Attempt 1:
Searching and reading the doc, I tried this way:
@action(methods=['put'], detail=False)
def update_car(self, request, *args, **kwargs):
if request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CarSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
But I received this error:
non_field_errors:
["Expected a list of items but got type "dict"."]
Attempt 2:
With a @fxgx I tried too:
def update_car(self, request):
serializer = CarSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = dict(list(serializer.validated_data.items()))
queryset = Car.objects.update(**validated_data)
return Response(CarSerializer(queryset, many=True).data)
But I received this error:
"detail": "Not found."
python django django-rest-framework
I'm studying django rest framework and would like the create a function. In this function, I need to pass a list in JSON and update by serializer.
For help I wrote a code example below.
Serialzer example:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
class CarViewSet(RestrictedQuerysetMixin, viewsets.ModelViewSet):
queryset = Car.objects.all()
serializer_class = CarSerializer
model = Car
Well. I need to update a car list through the garage serializer. I'm thinking anything like this:
(example view)
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=True, methods=['put'])
def update_car(self, request):
...
serializer = CarSerializer(queryset, many=True)
...
return Response(serializer.data)
Attempt 1:
Searching and reading the doc, I tried this way:
@action(methods=['put'], detail=False)
def update_car(self, request, *args, **kwargs):
if request.method == 'PUT':
data = JSONParser().parse(request)
serializer = CarSerializer(data=data, many=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
But I received this error:
non_field_errors:
["Expected a list of items but got type "dict"."]
Attempt 2:
With a @fxgx I tried too:
def update_car(self, request):
serializer = CarSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = dict(list(serializer.validated_data.items()))
queryset = Car.objects.update(**validated_data)
return Response(CarSerializer(queryset, many=True).data)
But I received this error:
"detail": "Not found."
python django django-rest-framework
python django django-rest-framework
edited Apr 2 at 20:54
Joey Fran
asked Mar 28 at 21:15
Joey FranJoey Fran
788 bronze badges
788 bronze badges
add a comment
|
add a comment
|
1 Answer
1
active
oldest
votes
DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=False, methods=['put'])
def update_car(self, request):
...
# Use partial=True for partial updates.
serializer = CarSerializer(data=request.data)
# Validate data.
serializer.is_valid(raise_exception=True)
# Get validated data in dictionary format.
validated_data = dict(list(serializer.validated_data.items()))
# Update objects
quertset.update(**validated_data)
...
return Response(CarSerializer(queryset, many=True).data)
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url examplerouter.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receiveupdate_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406952%2fhow-better-way-to-create-a-function-to-pass-a-json-by-serializer-in-django-rest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=False, methods=['put'])
def update_car(self, request):
...
# Use partial=True for partial updates.
serializer = CarSerializer(data=request.data)
# Validate data.
serializer.is_valid(raise_exception=True)
# Get validated data in dictionary format.
validated_data = dict(list(serializer.validated_data.items()))
# Update objects
quertset.update(**validated_data)
...
return Response(CarSerializer(queryset, many=True).data)
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url examplerouter.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receiveupdate_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
|
show 3 more comments
DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=False, methods=['put'])
def update_car(self, request):
...
# Use partial=True for partial updates.
serializer = CarSerializer(data=request.data)
# Validate data.
serializer.is_valid(raise_exception=True)
# Get validated data in dictionary format.
validated_data = dict(list(serializer.validated_data.items()))
# Update objects
quertset.update(**validated_data)
...
return Response(CarSerializer(queryset, many=True).data)
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url examplerouter.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receiveupdate_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
|
show 3 more comments
DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=False, methods=['put'])
def update_car(self, request):
...
# Use partial=True for partial updates.
serializer = CarSerializer(data=request.data)
# Validate data.
serializer.is_valid(raise_exception=True)
# Get validated data in dictionary format.
validated_data = dict(list(serializer.validated_data.items()))
# Update objects
quertset.update(**validated_data)
...
return Response(CarSerializer(queryset, many=True).data)
DRF serializers do not support bulk updates, you must pass an object instance to serializer to update it. What you can do is serializing data using serializer, updating objects with validated data and then serializing objects again to get response data:
class GarageViewSet(viewsets.ModelViewSet):
queryset = Garage.objects.all()
serializer_class = GarageSerializer
model = Garage
@action(detail=False, methods=['put'])
def update_car(self, request):
...
# Use partial=True for partial updates.
serializer = CarSerializer(data=request.data)
# Validate data.
serializer.is_valid(raise_exception=True)
# Get validated data in dictionary format.
validated_data = dict(list(serializer.validated_data.items()))
# Update objects
quertset.update(**validated_data)
...
return Response(CarSerializer(queryset, many=True).data)
edited Apr 2 at 22:55
answered Apr 2 at 20:32
zeynelzeynel
6954 silver badges12 bronze badges
6954 silver badges12 bronze badges
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url examplerouter.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receiveupdate_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
|
show 3 more comments
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url examplerouter.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receiveupdate_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
Hey @fxgx. Thank you. I tried something like your help. I will test now and send feedback.
– Joey Fran
Apr 2 at 20:39
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
I has some doubts about your example... I update my question.
– Joey Fran
Apr 2 at 20:55
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
@JoeyFran you defined this view as detail, which means you are taking this action on a Garage object. Are you sure that you are giving right Garage id to your url ?
– zeynel
Apr 2 at 21:04
My url example
router.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
My url example
router.register(r"garage", GarageViewSet, base_name="garage")
. I'm did not giving the id to url, sorry. Giving a id I receive update_car() got an unexpected keyword argument 'pk'
– Joey Fran
Apr 2 at 21:44
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
Okay, let me ask that. Do you want to update all the cars or do you want to update all the cars that belongs to a Garage? If you want second one, please update the question and put your Garage and Car models there so that i can help.
– zeynel
Apr 2 at 22:25
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406952%2fhow-better-way-to-create-a-function-to-pass-a-json-by-serializer-in-django-rest%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown