Comments (2)
This is a problem with DRF itself, as Flex fields does not interact with how the queryset is passed to the field for serialization, drf handles all that.
This is clear looking at the code, in ModelSerializer.build_relational_field
:
def build_relational_field(self, field_name, relation_info):
"""
Create fields for forward and reverse relationships.
"""
field_class = self.serializer_related_field
field_kwargs = get_relation_kwargs(field_name, relation_info) # here
to_field = field_kwargs.pop('to_field', None)
if to_field and not relation_info.reverse and not relation_info.related_model._meta.get_field(to_field).primary_key:
field_kwargs['slug_field'] = to_field
field_class = self.serializer_related_to_field
# `view_name` is only valid for hyperlinked relationships.
if not issubclass(field_class, HyperlinkedRelatedField):
field_kwargs.pop('view_name', None)
return field_class, field_kwargs
We get the queryset to be passed to the field from the get_relation_kwargs
function. Looking into it:
def get_relation_kwargs(field_name, relation_info):
"""
Creates a default instance of a flat relational field.
"""
model_field, related_model, to_many, to_field, has_through_model, reverse = relation_info
kwargs = {
'queryset': related_model._default_manager,
'view_name': get_detail_view_name(related_model)
}
if to_many:
kwargs['many'] = True
if to_field:
kwargs['to_field'] = to_field
limit_choices_to = model_field and model_field.get_limit_choices_to()
if limit_choices_to:
if not isinstance(limit_choices_to, models.Q):
limit_choices_to = models.Q(**limit_choices_to)
kwargs['queryset'] = kwargs['queryset'].filter(limit_choices_to)
if has_through_model:
kwargs['read_only'] = True
kwargs.pop('queryset', None)
if model_field:
if model_field.verbose_name and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
help_text = model_field.help_text
if help_text:
kwargs['help_text'] = help_text
if not model_field.editable:
kwargs['read_only'] = True
kwargs.pop('queryset', None)
if kwargs.get('read_only', False):
# If this field is read-only, then return early.
# No further keyword arguments are valid.
return kwargs
if model_field.has_default() or model_field.blank or model_field.null:
kwargs['required'] = False
if model_field.null:
kwargs['allow_null'] = True
if model_field.validators:
kwargs['validators'] = model_field.validators
if getattr(model_field, 'unique', False):
validator = UniqueValidator(queryset=model_field.model._default_manager)
kwargs['validators'] = kwargs.get('validators', []) + [validator]
if to_many and not model_field.blank:
kwargs['allow_empty'] = False
return kwargs
The relevant section is this:
kwargs = {
'queryset': related_model._default_manager,
'view_name': get_detail_view_name(related_model)
}
if to_many:
kwargs['many'] = True
This is then passed to a subclass of RelatedField
, which has the following get_queryset
method:
def get_queryset(self):
queryset = self.queryset
if isinstance(queryset, (QuerySet, Manager))
queryset = queryset.all()
return queryset
You can see that at no point you can limit the ammount of related objects returned in drf, so this should be raised with them. There are some SO questions relating to this and the solution seems to be to use a SerializerMethodField
.
https://stackoverflow.com/questions/52808869/how-to-limit-the-number-of-objects-given-from-nested-serialization
https://stackoverflow.com/questions/63321163/specifying-number-of-objects-to-serialize-drf
from drf-flex-fields.
Thank you for the detailed response and examples. Closing and will pursue other avenues.
from drf-flex-fields.
Related Issues (20)
- FlexFieldsFilterBackend does not handle "GenericForeignKey" HOT 2
- 0.9.9 not available on Pypi? HOT 1
- Expand Argument Not Respected When Empty HOT 1
- Release 1.0.0 available on PyPI but not listed in GIthub Releases, and not tagged
- is_expanded does not take into account the wildcard "*" (default) or setting "WILDCARD_VALUES"
- maximum depth of expansion (dot notation) / avoid infinite recursion HOT 2
- <module_path_to_serializer_class>.RelatedSerializer? HOT 1
- _get_expandable_fields() returns a list but is used by get_schema_fields() to concatenate str
- Swagger does not work when add FlexFieldsFilterBackend in my view
- Passing context to serializer with `request` param causes `AttributeError` on `query_params` HOT 6
- support Django 4.2 and drf 3.14??? HOT 3
- Applying distinct to `fields`
- Does "deferred field" imply under-the-hood `.defer()`? HOT 2
- Support for a list of expansions with multiple expand parameters instead of separated by a comma. HOT 1
- Support lazily evaluating expanded serializer class from a function
- Custom EXPAND_PARAM not usable in Serializer options HOT 1
- Enhancement Request: Support default expansion and omission of fields per drf view or action HOT 1
- Better notation for deferred fields? HOT 1
- OpenAPI support for query parameters HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from drf-flex-fields.