发布于2024-10-31 21:12 阅读(676) 评论(0) 点赞(6) 收藏(0)
I am working with Django REST Framework and trying to dynamically add fields to a serializer based on data selected from the UI. Specifically, I need to add fields for each commodity associated with a KindTournamentSerializer instance. These fields should represent the quantity of each commodity.
from rest_framework import serializers
class KindTournamentSerializer(CelestialSerializer):
voucher_id = serializers.CharField(label=_("Ration number"))
voucher_size = serializers.CharField(label=_("Ration size"))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Dynamically determine commodities from the instance
if self.instance:
selected_fields = kwargs.get('selected_fields', [])
if 'voucher_size' in selected_fields:
# Get the first instance to extract commodities
first_instance = self.instance[0] if isinstance(self.instance, TournamentSerializer) else self.instance
commodities = first_instance.rations.all()
# Create fields for each commodity
for ration in commodities:
commodity_name = ration.name
sanitized_name = commodity_name.replace(" ", "_").replace("-", "_")
field_name = f"commodity_{sanitized_name}"
# Add the SerializerMethodField
commodity_field = serializers.SerializerMethodField(label=_(commodity_name))
self.fields[field_name] = commodity_field
# Dynamically bind the method for the field
setattr(self, f'get_{field_name}', lambda obj, name=commodity_name: self.get_commodity_value(obj, name))
def get_commodities_data(self, obj):
"""Aggregate quantities of commodities from the latest voucher."""
latest_voucher = obj.latest_voucher
commodity_data = {}
if latest_voucher:
commodities = latest_voucher.commodities.all()
for commodity in commodities:
name = commodity.name
quantity = commodity.quantity
if name not in commodity_data:
commodity_data[name] = 0
commodity_data[name] += quantity
return commodity_data
def get_commodity_value(self, obj, commodity_name):
"""Retrieve the quantity of a specific commodity."""
commodities_data = self.get_commodities_data(obj)
return commodities_data.get(commodity_name, 0)
def to_representation(self, obj):
"""Customize representation to include commodity quantities."""
data = super().to_representation(obj)
# Add dynamic commodity fields to the representation
commodities_data = self.get_commodities_data(obj)
for field in self.fields:
if field.startswith("commodity_"):
commodity_name = field.replace("commodity_", "")
data[field] = commodities_data.get(commodity_name, 0)
return data
One of the numerous issues with the way it is defined above is that. When we call KindTournamentSerializer._declared_fields
from a CSV Exporter that uses this serializer.. The __init__
method is not trigger so those dynamic fields are not created.
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/2040412/68b4e22f44f17f93f22d/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!