Skip to content

Including lists of resources from non-model annotated objects #704

Closed
@RobinRamael

Description

@RobinRamael

I have a Organization model with a serializer whose instances get some extra data bound to then when using a specific view. this extra data is two lists of Product objects, which is not a django model (just a plain old python object) but its representation should look like a regular relation: the attrs for the organization and then the product lists in included. I tried the following:

class OrganizationSerializer(serializers.ModelSerializer):
    included_serializers = {
        "current_cycle": ProductSerializer,
        "next_cycle": ProductSerializer,
    }

    current_cycle = ResourceRelatedField(
        many=True, read_only=True, model=Product
    )
    next_cycle = ResourceRelatedField(
        many=True, read_only=True, model=Product
    )

    class Meta:
        model = Organization
        fields = ("pk", "current_cycle", "next_cycle")

    class JSONAPIMeta:
        included_resources = ("current_cycle", "next_cycle")

But this results in AttributeError: type object 'Organization' has no attribute 'current_cycle', which happens in utils.get_related_resource_type.

Stepping through the code there, it seems like although it's checking the model attribute directly on the relation, it's not reaching into the child_relation attr when the many is set to True. It does a child attribute which in my case wasn't there although child_relation is.

Doing a quick and dirty fix by including

    elif (
        hasattr(relation, "child_relation")
        and hasattr(relation.child_relation, "model"
    )):
        relation_model = relation.child_relation.model

in the big if/elif/else in get_related_resource_type seems to work. I'm however bery new to this library and maybe I'm just missing something. Otherwise I can make a PR with this fix, of course. Any help would be greatly appreciated :) Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions