def put(self, request): initial_user = User.objects.get(pk=request.user.id) updated_user = UserSerializer(initial_user, data=request.data) if (updated_user.is_valid()): initial_user = updated_user initial_user.save() return Response(initial_user.data) return Response(updated_user.errors, status=HTTP_422_UNPROCESSABLE_ENTITY)
class PopulatedCategorySerializer(CategorySerializer): destinations = DestinationSerializer(many=True, read_only=True) user = UserSerializer(read_only=True) class Meta(CategorySerializer.Meta): fields = ('id', 'name', 'destinations', 'user',)
def get(self, req): # get all users all_users = User.objects.all() users_leaderboard = [] # Go through each user and sum all their orders. Save the users' total to the database for user in all_users: user.total_money = user.money # get orders user_orders = Order.objects.filter(user=user.id).filter( active=True) for order in user_orders: # get property property_owned = Property.objects.get( pk=order.property_detail.id) # Add the value of their investment to the users total_money user.total_money += property_owned.current_valuation * order.ownership # If user has exactly £500k, they have never made any investements at all so should not be included if user.total_money != 500000: users_leaderboard.append(user) user.save() # Sort List in decending order by total money users_leaderboard.sort(key=self.most_money, reverse=True) serialized_leaderboard = UserSerializer(users_leaderboard, many=True) # Only send first 20 users return Response(serialized_leaderboard.data[:20])
class CommentSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) workspace = WorkspaceSerializer(read_only=True) class Meta: model = Comment fields = ('id', 'content', 'user', 'created_at', 'workspace',)
class WorkspaceSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Workspace fields = ('id', 'name', 'address_line_1', 'address_line_2', 'city', 'postcode', 'description', 'opening_times_mon', 'opening_times_tue', 'opening_times_wed', 'opening_times_thur', 'opening_times_fri', 'opening_times_sat', 'opening_times_sun', 'closing_times_mon', 'closing_times_tue', 'closing_times_wed', 'closing_times_thur', 'closing_times_fri', 'closing_times_sat', 'closing_times_sun', 'image', 'link', 'user', 'genres', 'bookmarks', )
class PopulatedCompanySerializer(serializers.ModelSerializer): offers = OfferSerializer(many=True) user = UserSerializer() class Meta(CompanySerializer.Meta): fields = ('id', 'user', 'name', 'logo', 'location', 'industry', 'description', 'website', 'women_achievements', 'employees', 'women_employees_percentaje', 'offers')
class ExerciseSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Exercise fields = ('id', 'content', 'level', 'user', 'sketch', 'subjects',)
class BikeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Bike fields = 'id', 'title', 'brand', 'mainimage', 'slogan', 'mainbody', 'image0', 'image1', 'image2', 'image3', 'image4', 'image5', 'image6', 'image7', 'image8', 'image9', 'image10', 'image11', 'image12', 'image13', 'image14', 'image15', 'displacement', 'compressionRatio', 'bore', 'stroke', 'length', 'wheelbase', 'seatheight', 'clearance', 'trail', 'dryweight', 'fueltank', 'torque', 'torquerpm', 'horsepower', 'fuelconsumption', 'co2emissions', 'primarydrive', 'firstgear', 'secondgear', 'thirdgear', 'fourthgear', 'fifthgear', 'sixthgear', 'frontbrakes', 'rearbrakes', 'frontwheelmaterial', 'rearwheelmaterial', 'fronttyre', 'reartyre', 'types', 'year', 'user'
def jwt_token_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data }
class ArticleSerializer(serializers.ModelSerializer): author = UserSerializer() class Meta: model = Article fields = '__all__'
class PopulatedWorkspaceSerializer(WorkspaceSerializer): genres = GenreSerializer(many=True) # bookmarks = BookmarkSerializer(many=True) comments = CommentSerializer(many=True, read_only=True) user = UserSerializer() class Meta(WorkspaceSerializer.Meta): fields = '__all__'
class PopulatedMealSerializer(MealSerializer): comments = PopulatedCommentSerializer(many=True) user = UserSerializer() cuisine = CuisineSerializer() class Meta(MealSerializer.Meta): fields = '__all__'
def put(self, request): initial_user = User.objects.get(pk=request.user.id) updated_user = UserSerializer(initial_user, data=request.data) if (updated_user.is_valid()): initial_user = updated_user initial_user.save() new_user = User.objects.get(pk=request.user.id) user_data = PopulatedUserSerializer(new_user) badges = get_user_badges(user_data) score = get_user_score(user_data) test_user = User.objects.get(pk=request.user.id) test_user.score = score badge_user = UserSerializer(test_user) badge_user.data['badges'].clear() badge_user.data['badges'].extend(badges) updated_badge_user = UserSerializer(test_user, data=badge_user.data) if (updated_badge_user.is_valid()): test_user = updated_badge_user test_user.save() all_users = User.objects.all() serialized_userList = PopulatedUserSerializer(all_users, many=True) get_platform_badges(serialized_userList) return Response(test_user.data) return Response(updated_badge_user.errors, status=HTTP_422_UNPROCESSABLE_ENTITY) return Response(updated_user.errors, status=HTTP_422_UNPROCESSABLE_ENTITY)
def post(self, request, pk): try: like = Like.objects.get(owner=request.user.id, resource=pk) like.delete() except Like.DoesNotExist: user = UserSerializer(request.user) resource = Resource.objects.get(pk=pk) Like.objects.create(owner=user.instance, resource=resource) resource = Resource.objects.get( pk=pk) # get the post with the new like serialized_resource = PopulatedResourceSerializer(resource) return Response(serialized_resource.data)
class MealSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Meal fields = ( 'id', 'name', 'image', 'description', 'cuisine', 'user', )
class PopulatedProgrammeSerializer(ProgrammeSerializer): items = PopulatedItemSerializer(many=True) user = UserSerializer() class Meta(ProgrammeSerializer.Meta): fields = ( 'id', 'name', 'image', 'location', 'items', 'user', )
class GameSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Game fields = ( 'id', 'title', 'genre', 'year', 'image', 'user', )
def post(self, request): # deserialiser the data serializer = UserSerializer(data=request.data) if serializer.is_valid(): # auto sets user to be logged in user serializer = PopulatedUserSerializer() serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=422)
class ClientCreateSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Client fields = ( 'id', 'name', 'stage', 'value', 'priority', 'partner', 'referral', 'user', )
class StationSerializer(serializers.ModelSerializer): zone = NestedZoneSerializer() # here is that nested serializer being used lines = NestedLineSerializer(many=True) owner = UserSerializer() def create(self, data): zone_data = data.pop('zone') lines_data = data.pop('lines') station = Station(**data) station.zone = Zone.objects.get(**zone_data) lines = [Line.objects.get(**line_data) for line_data in lines_data] station.save() # <=== this was key to ensure the primary key existed before trying to make the nested MTM relationship station.lines.set(lines) return station class Meta: model = Station fields = ('id', 'name', 'lat', 'lon', 'is_night_tube', 'zone', 'lines', 'owner') # and the adding of zone field with use that nested version, with no reference to station.
class Meta: model = Category user = UserSerializer(read_only=True) fields = ('id', 'name', 'destinations', 'user',)
class PopulatedFoodSerializer(FoodSerializer): user = UserSerializer()
class PopulatedWishlistSerializer(WishlistSerializer): user = UserSerializer()
class PopulatedCommentSerializer(CommentSerializer): user = UserSerializer(read_only=True)
class PopulatedApplicantSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta(ApplicantSerializer.Meta): fields = ('id', 'user', 'firstname', 'lastname', 'image', 'headline', 'roles', 'linkedin', 'portfolio', 'github', 'cv', 'skills',)
class PopulatedActivitiesSerializer(ActivitiesSerializer): user = UserSerializer()
class PopulatedCommentSerializer(CommentSerializer): owner = UserSerializer()
class PopulatedConnectionsSerializer(ConnectionsSerializer): participants = UserSerializer(many=True)
class BasicConnectionsSeralizer(ConnectionsSerializer): participants = UserSerializer(many=True)
class DestinationSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Destination fields = ('id', 'name', 'airport', 'country', 'longitude', 'latitude', 'cost', 'image', 'description', 'user', 'categories',)