我有两个如下的序列化器。以下代码段的输出是Workers以及具有所有字段(ticket_counter
,ticket_counter_name
,worker
)的关联的票务计数器详细信息。但我只需要一个字段ticket_counter_name
。
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = WorkerToCounterSerializer(many=True, read_only=True)
class Meta:
model = User
fields = (
'username',
'ticket_counter',
)
class WorkerToCounterSerializer(serializers.ModelSerializer):
ticket_counter = SerializerMethodField()
ticket_counter_name = serializers.CharField(source='ticket_counter.ticket_counter_name')
class Meta:
model = WorkerToTicketCounter
list_serializer_class = FilteredListSerializer
fields = (
'ticket_counter',
'ticket_counter_name',
'worker',
)
def get_ticket_counter(self, obj):
return obj.ticket_counter.pk
class FilteredListSerializer(ListSerializer):
def to_representation(self, data):
data = data.filter(worker_to_ticket_counter_is_deleted=False)[:1]
return super(FilteredListSerializer, self).to_representation(data)
上面的代码片段输出什么
{
"username": "xxxxxxxxxxx",
"ticket_counter": [
{
"ticket_counter": 7,
"ticket_counter_name": "Entrance Counter",
"worker": 4,
}
]
}
但是我想要的是
{
"username": "xxxxxxxxxxx",
"ticket_counter": "Entrance Counter"
}
我只需要ticket_counter_name
的名称。就我而言,一个工人不能有两个ticket_counters。显然,它只给出一个ticket_counter
。可能吗?
编辑:使用字符串StringRelatedField
{
"username": "xxxxxxxxxxx",
"ticket_counter": [
"Entrance Counter",
"xxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxx"
]
}
编辑:WorkerToTicketCounter
模型
class WorkerToTicketCounter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
ticket_counter = models.ForeignKey(TicketCounter, related_name="workers")
worker = models.ForeignKey(User, related_name='ticket_counter')
worker_to_ticket_counter_is_deleted = models.BooleanField(default=False)
答案 0 :(得分:1)
如果我理解正确,则只需一个 SerializerMethodField 即可执行 过滤 和 字符串重新设置< / em> 。
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = serializers.SerializerMethodField(read_only=True)
def get_ticket_counter(self, user):
qs = user.ticket_counter.filter(worker_to_ticket_counter_is_deleted=False)
if qs.exists() and hasattr(qs.first().ticket_counter, 'ticket_counter_name'):
return qs.first().ticket_counter.ticket_counter_name
return None
class Meta:
model = User
fields = ('username', 'ticket_counter',)
答案 1 :(得分:0)
您可以使用StringRelatedField
:
class WorkerSerializer(serializers.ModelSerializer):
ticket_counter = StringRelatedField(many=True, read_only=True)
class Meta:
model = User
fields = (
'username',
'ticket_counter',
)
请注意,要使用StringRelatedField
,应在__str__
模型中添加WorkerToTicketCounter
方法:
class WorkerToTicketCounter:
...
def __str__(self):
return self.ticket_counter.ticket_counter_name