我有一个Item的模型序列化器。
$items = $myParcelShipment->getOrder()->getAllItems();
foreach($items as $item) {
$sku= $item->getSku();
}
$CUSTOMLIST = [HERE A COMMA SEPARATED LIST OF PRODUCT SKU'S]
用户序列化程序。
$data = array(
'ToAddress' => array(
'name' => trim($shippingAddress->getName()),
'postcode' => trim($shippingAddress->getPostcode()),
'street' => trim($streetData['streetname']),
'house_number' => trim($streetData['housenumber']),
'town' => $shippingAddress->getCity(),
),
'ProductCode' => $this->_getProductCodeData($myParcelShipment),
'custom_id' => $CUSTOMLIST,
);
但是在ItemSerialzer中,对于user字段,我想显示用户的id,first_name和last_name。我怎样才能做到这一点?我很抱歉,如果这是一个菜鸟问题,我只是一个初学者。谢谢。
答案 0 :(得分:4)
您可以使用DRF的source属性遍历外键字段。
class ItemSerializer(serializers.ModelSerializer):
user_id = serializers.CharField(source="user.id")
first_name = serializers.CharField(source="user.first_name")
last_name = serializers.CharField(source="user.last_name")
class Meta:
model = Item
fields = ('id', 'user', 'title', 'body', 'image','user_id', 'first_name', 'last_name')