class CommentSerializer(serializers.ModelSerializer): author = ProfileSerializer(required=False) createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') class Meta: model = Comment fields = ( 'id', 'author', 'body', 'createdAt', 'updatedAt', ) def create(self, validated_data): article = self.context['article'] author = self.context['author'] return Comment.objects.create(author=author, article=article, **validated_data) def get_created_at(self, instance): return instance.created_at.isoformat() def get_updated_at(self, instance): return instance.updated_at.isoformat()
class UserSerializer(serializers.ModelSerializer): """Handles serialization and deserialization of User objects.""" password = serializers.CharField(max_length=128, min_length=8, write_only=True) profile = ProfileSerializer(write_only=True) print(profile) bio = serializers.CharField(source='profile.bio', read_only=True) image = serializers.CharField( source='profile.image', read_only=True, default='https://avatars.dicebear.com/4.5/api/avataaars/.svg') class Meta: model = User fields = ('id', 'email', 'username', 'password', 'token', 'profile', 'bio', 'image', 'is_staff') read_only_fields = ('token', ) def update(self, instance, validated_data): """Performs an update on a User.""" password = validated_data.pop('password', None) profile_data = validated_data.pop('profile', {}) # print(validated_data.pop('profile', {})) # print(profile_data) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() for (key, value) in profile_data.items(): setattr(instance.profile, key, value) instance.profile.save() return instance
class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=128, min_length=8, write_only=True) profile = ProfileSerializer(write_only=True) bio = serializers.CharField(source='profile.bio', read_only=True) image = serializers.CharField(source='profile.image', read_only=True) last_seen = serializers.CharField(source='get_last_seen') class Meta: model = User fields = ('id', 'email', 'username', 'password', 'token', 'profile', 'bio', 'image', 'is_admin', 'is_active', 'online', 'last_seen') read_only_fields = ('token', ) def update(self, instance, validated_data): password = validated_data.pop('password', None) profile_data = validated_data.pop('profile', {}) for (key, value) in validated_data.items(): setattr(instance, key, value) if password is not None: instance.set_password(password) instance.save() for (key, value) in profile_data.items(): setattr(instance.profile, key, value) instance.profile.save() return instance
class TrainingSerializer(serializers.ModelSerializer): difficulties = DifficultySerializer( many=True, source="exercices_t" ) #SOURCE HACE REFERENCIA A RELATED_NAME EN MODELO TRAINING/MODELS.PY DE author = ProfileSerializer(read_only=True) class Meta: model = Training fields = [ 'id', 'name', 'slug', 'image', 'description', 'verified', 'author', 'difficulties' ] def create(self, validated_data): difficulties_data = validated_data.pop('exercices_t') author = self.context.get('author', None) training = Training.objects.create(author=author, **validated_data) for difficultie in difficulties_data: d = dict(difficultie) Difficulty.objects.create(training=training, **d) return training
class TrainingSerializer(serializers.ModelSerializer): difficulties = DifficultySerializer(many=True, write_only=True) # exercices = serializers.ListField(read_only=True) exercices = serializers.SerializerMethodField() def get_exercices(self, obj): print("LELELELELELELELELELELELELELELELE") print(self) print(obj) ##SOLO FUNCIONA EN POST# SOLO MUESTRA EL ID DEL EJERCICIO data = self.__dict__.get('_kwargs').get('data').get('difficulties') print(data) return data # list_exer = list() # for value, dset in zip(entry[1:], data[entry[0]]): # # list_exer.add(value) # for diff in data: # exer = Exercice.objects.get(id=diff.get('exercice')) # # exer =Difficulty.objects.bulk_create(diff.get('exercice')) # list_exer.append(exer) # # print(exer) # print(list_exer) # json_data = json.dumps(list_exer) # objects = [] # for month, sales, expenses in zip(*my_list): # objects.append(MyModel( # month=month, # sales=sales, # expenses=expenses # )) # MyModel.objects.bulk_create(objects) # exers = Comment.objects.filter(track__in=obj.tracks.all()) # return CommentSerializer(comments, many=True).data # data.set(list_exer) # return DifficultySerializer(data, many=True).data #declaramos tambien exercices_id para al realizar el insert pongamos solo las ID (write only) # exercices_id = serializers.PrimaryKeyRelatedField(queryset=Exercice.objects.all(), write_only=True,many=True) # difs = DifficultySerializer(many=True, read_only=True) author = ProfileSerializer(read_only=True) description = serializers.CharField(required=False) verified = serializers.BooleanField(default=False) # difs = serializers.SerializerMethodField() # def get_difs(self,obj): class Meta: model = Training fields = [ 'id', 'name', 'slug', 'image', 'description', 'verified', 'author', 'difficulties', 'exercices' ] def create(self, validated_data): difficulties_data = validated_data.pop('difficulties') # exercices = Difficulty.objects.create(**exercices_data) author = self.context.get('author', None) training = Training.objects.create(author=author, **validated_data) # for exercice in exercices_data: # exercices_list.append(Difficulty.objects.create(**exercice, training = training)) # print(exercices_list) # training.exercices.set(exercices_list) # training.save() dif_list = [] for dif_data in difficulties_data: print("EXERCICE") # print(dif_data) Difficulty.objects.create(**dif_data, training=training) # dif_list.append(ex_c) # exercices = "holaholahola" # ex_c.exercice.all() # training.exercices.append(**dif_list) # print(dif_list) # training.difficulties_set.all() # for dif in difficulties_data: # # Exercice.objects.get(="Cheddar Talk") # print(b) return training # Group.objects.create(member=member, **group) # for memberhip in memberships: # Membership.objects.create(group=group, **memberships) # print(dict(exercice.exercice_id)) # print(dict(exercice).get("exercice_id")) # exer_id = exercice.exercice_id # exercice_c = Difficulty.objects.create( training = training, exercice_id=dict(exercice).get("exercice_id")) # dif = Difficulty.objects.create(**diffff, training = training) # # training.difs.add(dif) # dif_list.append(dif) # dif.save() # training.difficulties.all() # dif.all() # print(exercice_c.pk) # training.create(**exercice) # for exercice in exercices # training = TrainingSerializer(exercices = exercice_c) # print(exercice_c.exercice.id) # training.exercices.create(exercice=exercice_c) # training.exercices.append(exercice_c) # print("CREATED") # print(exercice_c.pk) # print(training.exercices) # training.save() # print(exercice_c.pk) # training.exercices.add(exercice_c.pk) # print(training.exercices) # training.exercices.add(*exercices_data) # training.save() # training.exercices.append(exercices_data) # print(training) # a_list = [] # print(json.loads(json.dumps(exercices_data))) # training.exercices.set(exercices) # # print(dict(zip(exercices_data,range(len(exercices_data))))) # for exercice in exercices_data: # # print(index) # print(exercice) # print(exercice.__hash__()) # # a_list.append(exercice) # # training.exercices["uno"].append(exercice) # # print(dict(exercice)) # training.exercices.add(exercice) # # print(a_list) # # training.exercices.add(a_list) # print(training.exercices) # training.difficulties.set(dif_list) # class DifficultySerializer(serializers.ModelSerializer): # class Meta: # model = Difficulty # fields = ( # "sets", # "exercice", # "training", # 'duration', # 'repetitions' # ) # sets = serializers.CharField(required=False) # duration = serializers.CharField(required=False) # repetitions = serializers.CharField(required=False) # exercices = ExerciceSerializer(many=True, read_only=True) # exercices_id = serializers.PrimaryKeyRelatedField(queryset=Exercice.objects.all(), write_only=True,many=True) # class Meta: # model = Training # fields = ['id', 'exercices','exercices_id','sets','duration','repetitions'] # def create(self, validated_data): # exercices = validated_data.pop('exercices_id') # author = self.context.get('author', None) # training = Training.objects.create(author=author, **validated_data) # for exercice in exercices: # training.exercices.add(exercice) # return training
class ExerciceSerializer(serializers.ModelSerializer): #Declaramos categories como READ ONLY (ya que solo lo gastaremos para mostrar) categories = CategorySerializer(many=True, read_only=True) #declaramos tambien categories_id para al realizar el insert pongamos solo las ID (write only) categories_id = serializers.PrimaryKeyRelatedField( queryset=Category.objects.all(), write_only=True, many=True) author = ProfileSerializer(read_only=True) description = serializers.CharField(required=False) verified = serializers.BooleanField(default=False) favorited = serializers.SerializerMethodField() favoritesCount = serializers.SerializerMethodField( method_name='get_favorites_count') class Meta: model = Exercice #añadimos el campo categories y categories_id fields = ('id', 'slug', 'name', 'description', 'image', 'favorited', 'favoritesCount', 'author', 'verified', 'categories', 'categories_id') def create(self, validated_data): #a categories añadimos las ID insertadas al realizar el POST categories = validated_data.pop('categories_id') author = self.context.get('author', None) exercice = Exercice.objects.create(author=author, **validated_data) #hacemos un for por todas las categorias y las añadimos una a una a categories for category in categories: exercice.categories.add(category) return exercice def update(self, instance, validated_data): print(instance) #a categories añadimos las ID insertadas al realizar el POST categories = validated_data.pop('categories_id') author = self.context.get('author', None) for (key, value) in validated_data.items(): setattr(instance, key, value) instance.categories.set( []) #Elimanamos las categorias que tuviera anterioremente #hacemos un for por todas las categorias y las añadimos una a una a categories for category in categories: instance.categories.add(category) instance.save() return instance def get_favorited(self, instance): request = self.context.get('request', None) if request is None: return False # if not request.user.is_authenticated(): if not request.user.is_authenticated: return False return request.user.profile.has_favorited(instance) def get_favorites_count(self, instance): return instance.favorited_by.count()
class UserSerializer(serializers.ModelSerializer): """Handles serialization and deserialization of User objects.""" # Passwords must be at least 8 characters, but no more than 128 # characters. These values are the default provided by Django. We could # change them, but that would create extra work while introducing no real # benefit, so let's just stick with the defaults. password = serializers.CharField(max_length=128, min_length=8, write_only=True) # When a field should be handled as a serializer, we must explicitly say # so. Moreover, `UserSerializer` should never expose profile information, # so we set `write_only=True`. profile = ProfileSerializer(write_only=True) # print(profile) # We want to get the `bio` and `image` fields from the related Profile # model. bio = serializers.CharField(source='profile.bio', read_only=True) image = serializers.CharField(source='profile.image', read_only=True) class Meta: model = User fields = ('email', 'username', 'password', 'token', 'profile', 'bio', 'image') # The `read_only_fields` option is an alternative for explicitly # specifying the field with `read_only=True` like we did for password # above. The reason we want to use `read_only_fields` here is because # we don't need to specify anything else about the field. For the # password field, we needed to specify the `min_length` and # `max_length` properties too, but that isn't the case for the token # field. read_only_fields = ('token', ) def update(self, instance, validated_data): """Performs an update on a User.""" # Passwords should not be handled with `setattr`, unlike other fields. # This is because Django provides a function that handles hashing and # salting passwords, which is important for security. What that means # here is that we need to remove the password field from the # `validated_data` dictionary before iterating over it. password = validated_data.pop('password', None) # Like passwords, we have to handle profiles separately. To do that, # we remove the profile data from the `validated_data` dictionary. profile_data = validated_data.pop('profile', {}) # print(validated_data.pop('profile', {})) # print(profile_data) for (key, value) in validated_data.items(): # For the keys remaining in `validated_data`, we will set them on # the current `User` instance one at a time. setattr(instance, key, value) if password is not None: # `.set_password()` is the method mentioned above. It handles all # of the security stuff that we shouldn't be concerned with. instance.set_password(password) # Finally, after everything has been updated, we must explicitly save # the model. It's worth pointing out that `.set_password()` does not # save the model. instance.save() for (key, value) in profile_data.items(): # print(key) # print(value) # print(profile_data.items()) # We're doing the same thing as above, but this time we're making # changes to the Profile model. setattr(instance.profile, key, value) # Save the profile just like we saved the user. instance.profile.save() return instance
class ArticleSerializer(serializers.ModelSerializer): author = ProfileSerializer(read_only=True) description = serializers.CharField(required=False) slug = serializers.SlugField(required=False) favorited = serializers.SerializerMethodField() favoritesCount = serializers.SerializerMethodField( method_name='get_favorites_count') tagList = TagRelatedField(many=True, required=False, source='tags') # Django REST Framework makes it possible to create a read-only field that # gets it's value by calling a function. In this case, the client expects # `created_at` to be called `createdAt` and `updated_at` to be `updatedAt`. # `serializers.SerializerMethodField` is a good way to avoid having the # requirements of the client leak into our API. createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') class Meta: model = Article fields = ( 'author', 'body', 'createdAt', 'description', 'favorited', 'favoritesCount', 'slug', 'tagList', 'title', 'updatedAt', ) def create(self, validated_data): author = self.context.get('author', None) tags = validated_data.pop('tags', []) article = Article.objects.create(author=author, **validated_data) for tag in tags: article.tags.add(tag) return article def get_created_at(self, instance): return instance.created_at.isoformat() def get_favorited(self, instance): request = self.context.get('request', None) if request is None: return False # if not request.user.is_authenticated(): if not request.user.is_authenticated: return False return request.user.profile.has_favorited(instance) def get_favorites_count(self, instance): return instance.favorited_by.count() def get_updated_at(self, instance): return instance.updated_at.isoformat()