Django Rest Framework different serializers for on model
I have Model, like:
def SomeModel(models.Model):
serial_num = models.IntegerField(unique=True)
count = models.IntegerField()
And have to create 2 url which will work with this model.
But, there are have to be 2 different serializers. For example:
- For first url user’data have to has both fileds (serial_num and
count) For second url users’data have to has only one field (count). - In second case serial_num will be generated in Serializers class.
Is this good practice to make 2 different serializers for one model?
And also question, what about validation?
Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls).
django django-rest-framework
|
show 1 more comment
I have Model, like:
def SomeModel(models.Model):
serial_num = models.IntegerField(unique=True)
count = models.IntegerField()
And have to create 2 url which will work with this model.
But, there are have to be 2 different serializers. For example:
- For first url user’data have to has both fileds (serial_num and
count) For second url users’data have to has only one field (count). - In second case serial_num will be generated in Serializers class.
Is this good practice to make 2 different serializers for one model?
And also question, what about validation?
Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls).
django django-rest-framework
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago
|
show 1 more comment
I have Model, like:
def SomeModel(models.Model):
serial_num = models.IntegerField(unique=True)
count = models.IntegerField()
And have to create 2 url which will work with this model.
But, there are have to be 2 different serializers. For example:
- For first url user’data have to has both fileds (serial_num and
count) For second url users’data have to has only one field (count). - In second case serial_num will be generated in Serializers class.
Is this good practice to make 2 different serializers for one model?
And also question, what about validation?
Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls).
django django-rest-framework
I have Model, like:
def SomeModel(models.Model):
serial_num = models.IntegerField(unique=True)
count = models.IntegerField()
And have to create 2 url which will work with this model.
But, there are have to be 2 different serializers. For example:
- For first url user’data have to has both fileds (serial_num and
count) For second url users’data have to has only one field (count). - In second case serial_num will be generated in Serializers class.
Is this good practice to make 2 different serializers for one model?
And also question, what about validation?
Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls).
django django-rest-framework
django django-rest-framework
asked 2 days ago
Mike
163112
163112
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago
|
show 1 more comment
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago
|
show 1 more comment
2 Answers
2
active
oldest
votes
You should use two serializers and use inheritance for common validation logic.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
Create two serializers and assign each of your views to that specific serializer.
for example, imagine you have two path like path1 and path2:
class MyModelViewSet(ModelViewSet):
serializer_class = Serializer1
queryset = YourModel.objects.all()
@action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
def path1_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
@action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
def path2_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
and for serializers:
class Serializer1(ModelSerializer):
class Meta:
model = SomeModel
fields = ('serial_num', 'count',)
class Serializer2(ModelSerializer):
class Meta:
model = SomeModel
fields = ('count',)
def validate(self, attrs):
# Update attrs with serial_num here
return attrs
For viewset actions likelist,create,update, etc you must overrideget_serializer_class()method and return the correct serializer class based on theself.actionattribute. Check this
– Lucas Weyne
2 days ago
add a comment |
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/3.0/"u003ecc by-sa 3.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%2f53945491%2fdjango-rest-framework-different-serializers-for-on-model%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You should use two serializers and use inheritance for common validation logic.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
You should use two serializers and use inheritance for common validation logic.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
You should use two serializers and use inheritance for common validation logic.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You should use two serializers and use inheritance for common validation logic.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 2 days ago
Ivan Cvetković
91
91
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
add a comment |
Create two serializers and assign each of your views to that specific serializer.
for example, imagine you have two path like path1 and path2:
class MyModelViewSet(ModelViewSet):
serializer_class = Serializer1
queryset = YourModel.objects.all()
@action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
def path1_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
@action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
def path2_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
and for serializers:
class Serializer1(ModelSerializer):
class Meta:
model = SomeModel
fields = ('serial_num', 'count',)
class Serializer2(ModelSerializer):
class Meta:
model = SomeModel
fields = ('count',)
def validate(self, attrs):
# Update attrs with serial_num here
return attrs
For viewset actions likelist,create,update, etc you must overrideget_serializer_class()method and return the correct serializer class based on theself.actionattribute. Check this
– Lucas Weyne
2 days ago
add a comment |
Create two serializers and assign each of your views to that specific serializer.
for example, imagine you have two path like path1 and path2:
class MyModelViewSet(ModelViewSet):
serializer_class = Serializer1
queryset = YourModel.objects.all()
@action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
def path1_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
@action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
def path2_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
and for serializers:
class Serializer1(ModelSerializer):
class Meta:
model = SomeModel
fields = ('serial_num', 'count',)
class Serializer2(ModelSerializer):
class Meta:
model = SomeModel
fields = ('count',)
def validate(self, attrs):
# Update attrs with serial_num here
return attrs
For viewset actions likelist,create,update, etc you must overrideget_serializer_class()method and return the correct serializer class based on theself.actionattribute. Check this
– Lucas Weyne
2 days ago
add a comment |
Create two serializers and assign each of your views to that specific serializer.
for example, imagine you have two path like path1 and path2:
class MyModelViewSet(ModelViewSet):
serializer_class = Serializer1
queryset = YourModel.objects.all()
@action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
def path1_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
@action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
def path2_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
and for serializers:
class Serializer1(ModelSerializer):
class Meta:
model = SomeModel
fields = ('serial_num', 'count',)
class Serializer2(ModelSerializer):
class Meta:
model = SomeModel
fields = ('count',)
def validate(self, attrs):
# Update attrs with serial_num here
return attrs
Create two serializers and assign each of your views to that specific serializer.
for example, imagine you have two path like path1 and path2:
class MyModelViewSet(ModelViewSet):
serializer_class = Serializer1
queryset = YourModel.objects.all()
@action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
def path1_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
@action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
def path2_view(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
.....
and for serializers:
class Serializer1(ModelSerializer):
class Meta:
model = SomeModel
fields = ('serial_num', 'count',)
class Serializer2(ModelSerializer):
class Meta:
model = SomeModel
fields = ('count',)
def validate(self, attrs):
# Update attrs with serial_num here
return attrs
edited 2 days ago
Lucas Weyne
926
926
answered 2 days ago
Reza Torkaman Ahmadi
596115
596115
For viewset actions likelist,create,update, etc you must overrideget_serializer_class()method and return the correct serializer class based on theself.actionattribute. Check this
– Lucas Weyne
2 days ago
add a comment |
For viewset actions likelist,create,update, etc you must overrideget_serializer_class()method and return the correct serializer class based on theself.actionattribute. Check this
– Lucas Weyne
2 days ago
For viewset actions like
list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this– Lucas Weyne
2 days ago
For viewset actions like
list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this– Lucas Weyne
2 days ago
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2f53945491%2fdjango-rest-framework-different-serializers-for-on-model%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
I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago
But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago
yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago
Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago
What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago