Reputation: 1582
In Django Rest Framework, I've got a post model that can be filtered by both usernames from my user object, and country names from a country objects. It just adds a ?search=
to the end of the API. From the frontend, it uses the same form to add this query onto the end of the url. I'd like to avoid confusion of returning both country names and user names that are the same. For example, if someone searched for Ireland, by preventing users from making an account with the username Ireland, it would only return Posts with country Ireland associated with the post (ManyToMany relationship to posts).
Is anything like this possible outside of creating a user for every country?
edit: Not trying to change anything with searching, trying to blacklist usernames.
Upvotes: 0
Views: 568
Reputation: 51988
You can try like this:
pycountry
which provides the countries. You can install it using pip install pycountry
In your registration serializer, update the clean method like this:
import pycountry
class Register(serializer.ModelSerializer):
....
def validate_username(self, value):
country = filter(lambda x: x.name.lower() == value.lower(), pycountry.countries)
if len(list(country)) > 0:
raise serializers.ValidationError("Invalid username")
return value
It will check if the username is actually a country name.
Upvotes: 1
Reputation: 359
Your data model and workflow are not entirely clear from your question, but it sounds like you could update your API View's queryset with a Q object checking if ( search=country OR search=user ).
You can do this in your API View like so:
import from django.db.models import Q
class PostList(generics.ListAPIView):
def get_queryset(self):
return Post.objects.filter(
Q(user__username=self.kwargs['search']) | \
Q(country__name=self.kwargs['search'])
)
You can read more about Q queries in the Django Documentation for Queries.
Upvotes: 1