[英]Problem with .only() method, passing to Pagination / Serialization --- all fields are getting returned instead of the ones specified in only()
I am trying load some data into datatables.我正在尝试将一些数据加载到数据表中。 I am trying to specify columns in the model.objects query by using.only() --- at first glance at the resulting QuerySet, it does in fact look like the mySQL query is only asking for those columns.
我试图通过 using.only() 指定 model.objects 查询中的列 --- 乍一看生成的 QuerySet,它实际上看起来像 mySQL 查询只要求这些列。
However, When I try to pass the QuerySet into Paginator, and/or a Serializer, the result has ALL columns in it.但是,当我尝试将 QuerySet 传递给 Paginator 和/或序列化器时,结果中包含所有列。
I cannot use.values_list() because that does not return the nested objects that I need to have serialized as part of my specific column ask.我不能 use.values_list() 因为它不会返回我需要序列化的嵌套对象,作为我的特定列询问的一部分。 I am not sure what is happening to my.only()
我不确定 my.only() 发生了什么
db_result_object = model.objects.prefetch_related().filter(qs).order_by(asc+sort_by).only(*columns_to_return)
paginated_results = Paginator(db_result_object,results_per_page)
serialized_results = serializer(paginated_results.object_list,many=True)
paginated_results.object_list = serialized_results.data
return paginated_results
This one has tripped me up too.这一个也让我绊倒了。 In Django, calling
only()
doesn't return data equivalent to a SQL statement like this:在 Django 中,调用
only()
不会返回与 SQL 语句等效的数据,如下所示:
SELECT col_to_return_1, ... col_to_return_n
FROM appname_model
The reason it doesn't do it like this is because Django returns data to you not when you construct the QuerySet, but when you first access data from that QuerySet ( see lazy QuerySets ).它不这样做的原因是因为 Django 不是在您构造 QuerySet 时向您返回数据,而是在您首次访问该 QuerySet 中的数据时( 请参阅惰性 QuerySets )。
In the case of only()
(a specific example of what is called a deferred field) you still get all of the fields like you normally would, but the difference is that it isn't completely loaded in from the database immediately.在
only()
的情况下(称为延迟字段的特定示例),您仍然可以像往常一样获得所有字段,但不同之处在于它不会立即从数据库中完全加载。 When you access the data, it will only load the fields included in the only statement.当您访问数据时,它只会加载唯一语句中包含的字段。 Some useful docs here .
这里有一些有用的文档。
My recommendation would be to write your Serializer so that it is only taking care of the one specific filed, likely using a SerializerMethodField with another serializer to serialize your related fields.我的建议是编写您的序列化程序,以便它只处理一个特定的字段,可能使用带有另一个序列化程序的 SerializerMethodField 来序列化您的相关字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.