[英]modify django model field on serializer
我有一個模型定義
Class Book():
name = textfield()
edition = textfield()
如果圖書對象上有版本數據,我希望將書名作為“版本名稱”。 否則我只想歸還這本書。 我怎樣才能做到這一點? 我可以在書序列化器上使用序列化器方法嗎
class BookSerializer(
):
name = serializers.SerializerMethodField()
def get_name(self,book):
if book.edition:
return f"{book.edition}{book.name}"
return book.name
這樣,名稱將與版本號一起保存。 我不想用名字保存版本號。 如果有版本,我只希望序列化程序應將名稱字段返回為“版本名稱”,否則只有名稱但不將其保存在模型上。
這可能不是最好的方法,但它是我一直在做的。
通過覆蓋to_representation
函數,您只能更改序列化結果。
像這樣
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('name', 'edition')
def to_representation(self, instance:Book):
out = super().to_representation(instance)
# change the name to <name edition>
out['name'] = f"{instance.edition if instance.edition else ""} {instance.name}"
# remove the original 'edition' so it doesnt show in output
out.pop('edition')
所以這樣當你序列化bool obj時,你只會得到一個包含“{edition} {name}”的'name'字段,但是你仍然可以使用這個序列化器來反序列化並在以后構造一個Book obj。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.