I have more experience with C (intermediary expertise) and now working on something in Django Python.
I have a url function which directs a REST call to a views function. Now, I am trying to make a single url for passing an argument for both an ID (int) and an email (str/EmailField) to land on the same views function and I can then unpack the type of the arg sent and do something different.
I want the url to be argument type agnostic and then do the conditional check in the views function. But it looks like each time, the argument is sent as a str (even when the id is sent).
I believe there may be 2 things here I do not fully understand: perhaps the argument will always be sent to the view function as a str all the time? Or there may be an issue with my type checking (as you can see I am trying to cast the type of the arg and check if true. Seems more like a C method of doing stuff?
Thank you!
urls.py looks like
path('<arg>/', views.getUpdateDeleteAccount), ->> this is what I am trying to do
#path('<int:pk>/', views.getUpdateDeleteAccount), ->>> works in isolation
#path('<str:email>/', views.getUpdateDeleteAccount), -->>> works in isolation
view.py looks like
@api_view(['GET', 'PUT', 'DELETE'])
def getUpdateDeleteAccount(request, arg):
if type(int(arg)) is int:
print("account id search, arg type is ")
print(type(arg))
try:
account = Account.objects.get(id=arg)
except Account.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
elif type(EmailField(arg)) is EmailField:
print("email add search, arg type is ")
print(type(arg))
try:
account = Account.objects.get(emailAddress=arg)
except Account.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)