Skip to content

Nested routes allow creation of objects for another parent object #142

Open
@felipe-prenholato

Description

@felipe-prenholato

So, consider two models as example:

class User(AbstractUser):
    pass

class Account(Model):
    user = ForeignKey(settings.AUTH_USER_MODEL)
    avatar = URLField()

This router:

router.register(r"users", UserViewSet) \
      .register(r"accounts", AccountViewSet, base_name="users-accounts",
                parents_query_lookups=["user"])

Now if you issue a POST to /users/1/accounts/ with {"user": 2, "avatar": "www.example.com"} the account is created for user with ID 2 instead ID 1.

Serializers (which create the stuff in DB) will use request.data and request.data have {"user": "2"}. DRF-Extensions need to force the correct user in this situations.

One workaround to this problem is inject correct user in request.data, something like:

class NestedAccountViewSet(NestedViewSetMixin, AccountViewSet):

    def initialize_request(self, request, *args, **kwargs):
        """
        Inject user from url in request.data
        """
        request = super(NestedAccountViewSet, self).initialize_request(
            request, *args, **kwargs
        )
        if request.data:
            request.data["user"] = kwargs["parent_loookup_user"]

        return request

Change the request.data like code above is easy, but I'm sure that isn't the best way to do it. Maybe DRF-Extensions can offer some custom serializer that receive extra information from url regex or do some magic in views so we don't need to do this injection?

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions