Coder Social home page Coder Social logo

Comments (2)

Caiofcas avatar Caiofcas commented on August 13, 2024

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.

rdylanwalker avatar rdylanwalker commented on August 13, 2024

Thank you for the detailed response and examples. Closing and will pursue other avenues.

from drf-flex-fields.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.