Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can email field be used as a lookup field with django rest framework

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]

like image 886
codecrazy46 Avatar asked Oct 16 '25 16:10

codecrazy46


1 Answers

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.

like image 172
JPG Avatar answered Oct 19 '25 13:10

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!