Model Viewsets with no lookup field - Some hacks and some ideas. #8305
Replies: 2 comments
-
How did you end up handling this? |
Beta Was this translation helpful? Give feedback.
-
@ricky-sb I ended going fully rest, and ditching these "current user" endpoints. The way I did it was just returning the user ID in the login response so the client knows the user ID. From there I just used went fully REST and serialising the attributes)
Another "hack" I did to facilitate things was tho make User and the related One to One model share the same primary key:
That way I get the user id in the login response, and I can do this at the same time in parallel without waiting for the user endpoint to return the ID of the profile associated with the user:
Hope this helps |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm working on an API endpoint which is a 1-to-1 with the current logged in user. I want this endpoint to work on a single object, which is the object associated with the current logged in user, like so:
However, routers really require a
lookupfield
because of the URL generation. So I couldn't find any quick good approaches for this. I did come up with two hacks, which neither feel right to me:Using
as_view
+get_object
This means bypassing the router all together, and registering a path:
But this comes with some disadvantages, like automatic documentation, and other libraries that depend on the DRF router not working.
Hacking the lookup field
This approach basically means creating a lookup field shortcut in the viewset, so when we pass the lookupfield with the value
me
it will return the object associated with the current user:Discussion
I'm wondering what approaches other people used for these kinds of endpoints with DRF.
register
method receive an optionalurl
and the same arguments asas_view
does, to register these kinds of endpoints like:Beta Was this translation helpful? Give feedback.
All reactions