25π
β
Since youβd defined the __str__()
method in your Company
model, you can use the StringRelatedField()
as
class UserSerializer(serializers.ModelSerializer):
company_name = serializers.StringRelatedField()
class Meta:
model = User
fields = '__all__'
UPDATE
override the to_representation
method
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
def to_representation(self, instance):
rep = super(UserSerializer, self).to_representation(instance)
rep['company_name'] = instance.company_name.name
return rep
π€JPG
10π
simple solution is use source
class UserSerializer(serializers.ModelSerializer):
company_name = serializers.CharField(source='company_name.name')
π€Brown Bear
- How to connect Django in EC2 to a Postgres database in RDS?
- Clone an inherited django model instance
- How to remove the language identifier from django-cms 2.4 URLs?
4π
Use depth.
class PhoneSerializer(serializers.ModelSerializer):
class Meta:
model = Phone
depth = 1
fields = '__all__'
3π
class UserSerializer(serializers.ModelSerializer):
company_name = serializers.SerializerMethodField(source='get_company_name')
class Meta:
model = User
fields = '__all__'
def get_company_name(self, obj):
return obj.company_name.name
π€Exprator
1π
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
def to_representation(self, instance):
rep = super(UserSerializer, self).to_representation(instance)
rep['company_name'] = instance.company_name.name
return rep
π€Mrutyunjaya Rout
- Django β reverse query name clash
- How to extend the comments framework (django) by removing unnecessary fields?
0π
Here is the documentation:
This worked for me:
company_name = serializers.SlugRelatedField(read_only=True, slug_field='name')
π€Dragos Neata
- Determine if an attribute is a `DeferredAttribute` in django
- Django: Check for related objects and whether it contains data
- Django custom for complex Func (sql function)
- How to debug a Django MultiValueDictKeyError on Formset POST
- Error Using CheckConstraint in Model.Meta along with Django GenericForeignKey β Joined field references are not permitted in this query
Source:stackexchange.com