我有一个序列化程序,可以与对象pk进行POST并获取整个嵌套对象:
val spark = ...
import spark.implicits._
def readCsv[T: Encoder[T]](path: String): Dataset[T] = {
spark
.read
.option("header", "true")
.csv(path)
.as[T]
}
val infoDS = readCsv[InfoData]("/src/main/info.csv")
我的一些数据以FormData()来自我的React前端,因此它不是表示对象pk的整数列表,而是将其转换为字符串列表。发布到使用此序列化程序的Viewset时:
class CountryField(serializers.PrimaryKeyRelatedField):
'''
This serializer allows GET requests to return the full nested Country
object, but use the pk for POST/PUT/PATCH requests. This serializer is used
with the Trip Report and User Detail serializers to simplify handling
requests from the frontend. This serializer is used on the User & Trip
Report Views. This makes POST & PUT requests from the frontend easy to
maintain, e.g. the pk can be stored as the value of an option on a select
form, instead of having to store the entire country object.
'''
def to_representation(self, value):
pk = super(CountryField, self).to_representation(value)
try:
item = Country.objects.get(pk=pk)
serializer = CountrySerializer(item)
return serializer.data
except Country.DoesNotExist:
return None
def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
return {}
return OrderedDict([(item.id, str(item)) for item in queryset])
我收到错误类型错误。预期pk值,收到str。我在哪里可以编写一种方法来将该字符串列表转换为整数列表?
更多背景:在向模型中添加图像字段后,只需要将POST数据转换为FormData()。当我最初以pk列表发布时,我没有问题,但是现在它是FormData(),我得到了错误。