def get_city(request, city_id): """ Returns a city on the basis of city id :param request: :param city_id: :return: 404 if invalid city id is sent :return: 200 successful """ try: city = City.objects.get(pk=city_id) city.has_visited = Trip.objects.filter(city=city, users=request.user).exists() except City.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # Add city visit log try: city_visit_log = CityVisitLog(city=city, user=request.user) city_visit_log.save() except Exception: pass serializer = CitySerializer(city) return Response(serializer.data)
class TripSerializer(serializers.ModelSerializer): city = CitySerializer(many=False, read_only=True) users = UserSerializer(many=True, read_only=True) class Meta: model = Trip fields = ('id', 'trip_name', 'city', 'users', 'start_date_tx')
def get_all_cities(request): """ Returns a list of all the cities :param request: :return: """ if request.method == 'GET': cities = City.objects.all() serializer = CitySerializer(cities, many=True) return Response(serializer.data)
class TripCondensedSerializer(serializers.ModelSerializer): city = CitySerializer(many=False, read_only=True) users_count = serializers.SerializerMethodField() class Meta: model = Trip fields = ('id', 'trip_name', 'city', 'users_count', 'start_date_tx') def get_users_count(self, obj): return obj.users.count()
def get_city_by_name(request, city_prefix): """ Returns a list of cities that starts with the given city prefix :param request: :param city_prefix: :return: 200 successful """ cities = City.objects.filter(city_name__istartswith=city_prefix)[:5] serializer = CitySerializer(cities, many=True) return Response(serializer.data)
def get_all_cities(request, no_of_cities=8): """ Returns a list of all the cities :param request: :param no_of_cities: (default count: 8) :return: 200 successful """ cities = City.objects.all().order_by('-id')[:no_of_cities] serializer = CitySerializer(cities, many=True) return Response(serializer.data)
def get_city(request, city_id): """ Returns a city on the basis of city id :param request: :param city_id: :return: 404 if invalid city id is sent :return: 200 successful """ try: city = City.objects.get(pk=city_id) except City.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CitySerializer(city) return Response(serializer.data)
def get_city(request, city_id): """ Returns a city on the basis of city id :param request: :param city_id: :return: """ try: city = City.objects.get(pk=city_id) except City.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CitySerializer(city) return Response(serializer.data)