This would however work only for read only fields. The same principle applies if you want to change the return type on the API, so you can do serializers.DecimalField(source=.) and other field types as well. Location = serializers.CharField(source='OtherModel_other_fields') Location = serializers.CharField(source='other_fields')ĭjango's _ notation to traverse foreign key also works: Location = serializers.SerializerMethodField('get_alternate_name')Īdditionally, you can use serializers.CharField with source attribute: class ParkSerializer(serializers.ModelSerializer): class ParkSerializer(serializers.ModelSerializer): This changes the name of alternate_name to location. Here is Serializer for Park Model, ParkSerializer. class Park(models.Model):Īlternate_name = models.CharField(max_length=256, blank=True) Here is the model Park, which has name and alternate_name fields. You can use serializers.SerializerMethodField: It effectively creates one on one mapping of the field name in the serializer and field name in models. This works with the creation, deletion, and modification requests too. Locations = AlternateNameSerializer(source='alternate_name', many=true)Ĭlass AlternateNameSerializer(serializers.ModelSerialzer): ie even if alternate_name was a foreignkey field to another model. Also, you can put relational fields and other serializers instead and this would still work like charm. Where serializers.SomeSerializerField can be serializers.CharField as your model suggests but can also be any of the other fields. Location = serializers.SomeSerializerField(source='alternate_name') There is a very nice feature in serializer fields and serializers in general called 'source' where you can specify source of data from the model field.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |