Can an email field in the model be used as a lookup field for the rest api?
I have a model "User" with username=models.CharField() and email=models.EmailField() as members. I would like to set email as the lookup field in the viewset and have the below code for the same.
def get_queryset(self):
if 'email' in self.kwargs:
return User.objects.filter(email=self.kwargs['email'])
else:
return User.objects.all()
lookup_field = 'email'
lookup_url_kwarg = 'email'
However, since email field always contains a '.', the lookup fails with "current path didn't match any of these" message. How can we perform a successful api lookup with a value containing a '.' e.g. an email
GET /api/user/[email protected]
specify the lookup_value_regex
attribute in the viewset
class FooViewset(ModelViewSet):
queryset = Foo.objects.all()
serializer_class = FooSerializer
lookup_field = 'email'
lookup_url_kwarg = 'email'
lookup_value_regex = '[\w@.]+' # here is the new attribute
NOTE: You don't have to override the get_queryset()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With