How to Change ManyToManyField Name in SerializerDjango REST framework: non-model serializerHow to change field name in Django REST FrameworkDjango REST Errors when serializing model with ManyToManyFieldHow to get Request.User in Django-Rest-Framework serializer?depth = 1 doesn't work properly and it's saves Null in ManyToManyField and ForeignKey fields in Django Rest FrameworkHow to serialize GenericForeignKey in DRF?Django Rest Framework Serializer charfield not updating when source is givenSerializing ManyToManyField in DjangoRestFrameworkdjango ManyToManyField serializerLack of data with serialization model with ManyToManyField
How do I spend money in Sweden and Denmark?
How hard is it to sell a home which is currently mortgaged?
Why does the numerical solution of an ODE move away from an unstable equilibrium?
Can I travel from Germany to England alone as an unaccompanied minor?
In native German words, is Q always followed by U, as in English?
Why Is Abelian Gauge Theory So Special?
Should I tell my insurance company I have an unsecured loan for my new car?
Why is the Turkish president's surname spelt in Russian as Эрдоган, with г?
can’t run a function against EXEC
Was "I have the farts, again" broadcast from the Moon to the whole world?
Is there any set of 2-6 notes that doesn't have a chord name?
What does 2>&1 | tee mean?
does a number that contains all primes less than it exist?
Are there any vegetarian astronauts?
If a high rpm motor is run at lower rpm, will it produce more torque?
Cross over of arrows in a complex diagram
How can I convince my reader that I will not use a certain trope?
How exactly is a normal force exerted, at the molecular level?
Difference between 'demás' and 'otros'?
How to write or read powers (math) by words?
A player is constantly pestering me about rules, what do I do as a DM?
How fast can a ship with rotating habitats be accelerated?
Does the UK have a written constitution?
One folder two different locations on ubuntu 18.04
How to Change ManyToManyField Name in Serializer
Django REST framework: non-model serializerHow to change field name in Django REST FrameworkDjango REST Errors when serializing model with ManyToManyFieldHow to get Request.User in Django-Rest-Framework serializer?depth = 1 doesn't work properly and it's saves Null in ManyToManyField and ForeignKey fields in Django Rest FrameworkHow to serialize GenericForeignKey in DRF?Django Rest Framework Serializer charfield not updating when source is givenSerializing ManyToManyField in DjangoRestFrameworkdjango ManyToManyField serializerLack of data with serialization model with ManyToManyField
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I want to change ManyToManyField Name. user_groups
is manytomanyfield. I tried to use ManyToManyRelatedField and also PrimaryKeyRelatedField but it is giving error. How can i change or with data type should i give like for character field i am giving CharField
class EmployeeProfileSerializer(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id')
payroll_id = serializers.CharField(source='user_payroll_id')
phone = serializers.CharField(source='user_phone')
hire_date = serializers.DateField(source='user_hire_date')
pay_rate = serializers.IntegerField(source='user_pay_rate')
salaried = serializers.CharField(source='user_salaried')
excempt = serializers.CharField(source='user_excempt')
state = serializers.CharField(source='user_state')
city = serializers.CharField(source='user_city')
zipcode = serializers.IntegerField(source='user_zipcode')
status = serializers.CharField(source='user_status')
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'user_groups',
]
django django-rest-framework
add a comment |
I want to change ManyToManyField Name. user_groups
is manytomanyfield. I tried to use ManyToManyRelatedField and also PrimaryKeyRelatedField but it is giving error. How can i change or with data type should i give like for character field i am giving CharField
class EmployeeProfileSerializer(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id')
payroll_id = serializers.CharField(source='user_payroll_id')
phone = serializers.CharField(source='user_phone')
hire_date = serializers.DateField(source='user_hire_date')
pay_rate = serializers.IntegerField(source='user_pay_rate')
salaried = serializers.CharField(source='user_salaried')
excempt = serializers.CharField(source='user_excempt')
state = serializers.CharField(source='user_state')
city = serializers.CharField(source='user_city')
zipcode = serializers.IntegerField(source='user_zipcode')
status = serializers.CharField(source='user_status')
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'user_groups',
]
django django-rest-framework
add a comment |
I want to change ManyToManyField Name. user_groups
is manytomanyfield. I tried to use ManyToManyRelatedField and also PrimaryKeyRelatedField but it is giving error. How can i change or with data type should i give like for character field i am giving CharField
class EmployeeProfileSerializer(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id')
payroll_id = serializers.CharField(source='user_payroll_id')
phone = serializers.CharField(source='user_phone')
hire_date = serializers.DateField(source='user_hire_date')
pay_rate = serializers.IntegerField(source='user_pay_rate')
salaried = serializers.CharField(source='user_salaried')
excempt = serializers.CharField(source='user_excempt')
state = serializers.CharField(source='user_state')
city = serializers.CharField(source='user_city')
zipcode = serializers.IntegerField(source='user_zipcode')
status = serializers.CharField(source='user_status')
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'user_groups',
]
django django-rest-framework
I want to change ManyToManyField Name. user_groups
is manytomanyfield. I tried to use ManyToManyRelatedField and also PrimaryKeyRelatedField but it is giving error. How can i change or with data type should i give like for character field i am giving CharField
class EmployeeProfileSerializer(serializers.ModelSerializer):
employee_id = serializers.CharField(source='user_employee_id')
payroll_id = serializers.CharField(source='user_payroll_id')
phone = serializers.CharField(source='user_phone')
hire_date = serializers.DateField(source='user_hire_date')
pay_rate = serializers.IntegerField(source='user_pay_rate')
salaried = serializers.CharField(source='user_salaried')
excempt = serializers.CharField(source='user_excempt')
state = serializers.CharField(source='user_state')
city = serializers.CharField(source='user_city')
zipcode = serializers.IntegerField(source='user_zipcode')
status = serializers.CharField(source='user_status')
class Meta:
model = UserProfile
fields = [
'employee_id',
'phone',
'payroll_id',
'hire_date',
'pay_rate',
'salaried',
'excempt',
'state',
'city',
'zipcode',
'status',
'user_groups',
]
django django-rest-framework
django django-rest-framework
asked Mar 25 at 12:04
Huzaif SayyedHuzaif Sayyed
7431 silver badge20 bronze badges
7431 silver badge20 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
You can use SerializerMethodField
:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create
and update
method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call thevalidate
function or validate function for that field likedef validate_my_custom_name(self, value)
and use other fields likeCharField
and then override thesave
andupdate
method and get the data there and assign it to your model.
– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
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%2f55337413%2fhow-to-change-manytomanyfield-name-in-serializer%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
You can use SerializerMethodField
:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create
and update
method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call thevalidate
function or validate function for that field likedef validate_my_custom_name(self, value)
and use other fields likeCharField
and then override thesave
andupdate
method and get the data there and assign it to your model.
– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
add a comment |
You can use SerializerMethodField
:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create
and update
method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call thevalidate
function or validate function for that field likedef validate_my_custom_name(self, value)
and use other fields likeCharField
and then override thesave
andupdate
method and get the data there and assign it to your model.
– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
add a comment |
You can use SerializerMethodField
:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create
and update
method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...
You can use SerializerMethodField
:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = SerializerMethodField()
class Meta:
model = UserProfile
fields = ['your_custom_name ', ...]
def get_your_custom_name(self, obj):
# Return ids:
return list(obj.user_groups.all().values_list('pk', flat=True))
# Or using a serializer:
return MyUserGroupSerializer(obj.user_groups.all(), many=True).data
For create and update you have to override the create
and update
method to assign the new field:
class EmployeeProfileSerializer(serializers.ModelSerializer):
...
your_custom_name = IntegerField()
class Meta:
model = UserProfile
fields = ['your_custom_name', ...]
# If you need validation
def validate_your_custom_name(self, value):
if value:
if int(value) > 5:
return value
return None
def create(self, validated_data):
# Get the data for your new field
my_costum_data = validated_data.get('your_custom_name')
# Do something with it
profile_obj = UserProfile.objects.create(...)
if my_costum_data:
user_group = UserGroupModel.objects.get(pk=int(my_costum_data))
profile_obj.user_groups.add(user_group)
def update(self, instance, validated_data):
# Same as create()
...
edited Mar 25 at 20:12
answered Mar 25 at 12:08
Navid2zpNavid2zp
1,8051 gold badge6 silver badges18 bronze badges
1,8051 gold badge6 silver badges18 bronze badges
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call thevalidate
function or validate function for that field likedef validate_my_custom_name(self, value)
and use other fields likeCharField
and then override thesave
andupdate
method and get the data there and assign it to your model.
– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
add a comment |
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call thevalidate
function or validate function for that field likedef validate_my_custom_name(self, value)
and use other fields likeCharField
and then override thesave
andupdate
method and get the data there and assign it to your model.
– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
I am using this for create and update will it work
– Huzaif Sayyed
Mar 25 at 12:20
No, if you're using this for update and create, then you have to call the
validate
function or validate function for that field like def validate_my_custom_name(self, value)
and use other fields like CharField
and then override the save
and update
method and get the data there and assign it to your model.– Navid2zp
Mar 25 at 12:24
No, if you're using this for update and create, then you have to call the
validate
function or validate function for that field like def validate_my_custom_name(self, value)
and use other fields like CharField
and then override the save
and update
method and get the data there and assign it to your model.– Navid2zp
Mar 25 at 12:24
Check the answer for example
– Navid2zp
Mar 25 at 12:37
Check the answer for example
– Navid2zp
Mar 25 at 12:37
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.
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%2f55337413%2fhow-to-change-manytomanyfield-name-in-serializer%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