class ProblemSerializer(ModelSerializer): is_solved = SerializerMethodField() class Meta: class ListSerializer(ListSerializer): def to_representation(self, data): self.child.is_solved_set = set( Submission.objects. values_list('problem_id', flat=True).filter( user=self.context['request'].user, problem__in=data, verdict=VerdictResult.AC)) if self.context[ 'request'].user.is_authenticated else set() return super().to_representation(data) model = Problem fields = ('id', 'title', 'is_solved') # https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior # Have to do it this way, to actually overrite to_representation() list_serializer_class = ListSerializer def get_is_solved(self, obj): user = self.context['request'].user return user.is_authenticated and obj.id in self.is_solved_set
class PostDetailSerializer(ModelSerializer): url = post_detail_url author = UserDetailSerializer(read_only=True) image = SerializerMethodField() class Meta: model = Post fields = [ 'url', 'id', 'author', 'title', 'slug', 'text', 'published_date', 'image', ] def get_image(self, obj): try: image = obj.image.url except: image = None return image
class CommentDetailSerializer(Modelserializer): replies = SerializerMethodField() #the replies are the children class Meta: model = Comment fields = [ 'id', 'content_type', 'object_id', 'content', 'replies', 'timestamp', ] #====kinda tricky on this not getting it properly====== def get_replies(self, obj): if obj.is_parent: return CommentChildSerializer(obj.children(), many=True).data return None def get_reply_count(): if obj.is_parent: return obj.children().count() return 0
class PostDetailSerializer(serializers.ModelSerializer): comments = SerializerMethodField() #このフィールドを加えると下記のように出力する値を操作できます。 class Meta: model = Post fields = [ 'id', 'author', 'title', 'text', 'created_date', 'published_date', 'comments', #モデルには存在しない追加する新フィールド ] def get_comments(self, obj): try: comment_abstruct_contents = CommentChildSerializer(Comment.objects.all().filter(target_post = Post.objects.get(id=obj.id)), many=True).data #↑ここを"Comment.objects.all().filter(target_article = Article.objects.get(id=obj.id)" #とだけにすると、"Item is not JSON serializable"というエラーが出ますので #Serializer(出力させたいもの).data という処理が必要です。 return comment_abstruct_contents except: comment_abstruct_contents = None return comment_abstruct_contents
class SimpleDatasetSerializer(DynamicFieldsModelSerializer): url = HyperlinkedIdentityField(view_name='datasets:dataset-detail') publisher = HyperlinkedRelatedField( view_name='publishers:publisher-detail', read_only=True) type = SerializerMethodField() class Meta: model = Dataset fields = ( 'id', 'iati_id', 'type', 'url', 'name', 'title', 'filetype', 'publisher', 'source_url', 'iati_version', 'added_manually', ) def get_type(self, obj): return obj.get_filetype_display()
class NoticeSerializer(serializers.ModelSerializer): image = serializers.ImageField() like_btn = serializers.SerializerMethodField() like_user = serializers.StringRelatedField(many=True, source='get_like_user', read_only=True) like_user_count = SerializerMethodField() class Meta: model = Notice fields = [ 'like_btn', 'pk', 'image', 'title', 'text', 'like_user', 'like_user_count', 'hit', 'created_at', 'updated_at', ] read_only_fields = [ 'pk', 'created_at', 'updated_NoticeSerializerat', ] def get_like_btn(self, obj): return reverse_lazy('api-stores:notice-like', kwargs={'notice_pk': obj.pk}) def get_like_user_count(self, obj): return obj.like_user.count()
class QuestionListSerializer(ModelSerializer): """ This serializer serializes the Question model It should also include a field "choices" that will serialize all the choices for a question You well need a SerializerMethodField for choices, http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield Reference this stack overflow for the choices: https://stackoverflow.com/questions/33945148/return-nested-serializer-in-serializer-method-field """ #Declare class attribute from child model/table to be serialized choices = SerializerMethodField()#serialize choices for given question #Declare metaclass and specify meta behavior class Meta: model = Question fields = ('id','text', 'pub_date', 'choices') #list of fields in the Question Model #with reference to foreign entity 'choices' #Declare attribute functions for getting out serializable data from child table/model def get_choices(self, obj): choices = obj.choice_set.all() return ChoiceSerializer(choices, many=True).data
class CommentListSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name='comments-api:thread' ) reply_count = SerializerMethodField() class Meta: model = Comment fields = [ 'id', 'url', # 'content_type', # 'object_id', # 'parent', 'content', 'reply_count', 'timestamp', ] # extra_kwargs = {'request': request} def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0
class QuestionListSerializer(ModelSerializer): """ This serializer serializes the Question model It should also include a field "choices" that will serialize all the choices for a question You well need a SerializerMethodField for choices, http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield Reference this stack overflow for the choices: https://stackoverflow.com/questions/33945148/return-nested-serializer-in-serializer-method-field """ #choice = serializers.SerializerMethodField(source='get_question_choices') #def get_question_choices(self, obj): # choices = obj.choice_set.all() # return ChoiceSerializer(choices, many=True).data choices = SerializerMethodField(source='get_choices', read_only=True) def get_choices(self, obj): question_choices = obj.choice_set.all() return ChoiceSerializer(question_choices, many=True).data class Meta: model = Question fields = ('id', 'text', 'pub_date', 'choices')
class NotificationSerializer(ModelSerializer): """ Serializer of a notification object. """ content_type = SerializerMethodField() subscription = SubscriptionSerializer() sender = UserListSerializer() class Meta: model = Notification fields = ( 'id', 'title', 'is_read', 'url', 'sender', 'pubdate', 'content_type', 'subscription', ) permissions_classes = DRYPermissions def get_content_type(self, obj): return obj.content_type.model
class FeedSerializer(ModelSerializer): user = User() username = SerializerMethodField() picture = URLField(source='get_picture', read_only=True) class Meta: model = Feed fields = [ 'id', 'user', 'picture', 'username', 'date', 'parent', 'post', 'likes', 'comments', ] def get_username(self, obj): return str(obj.user.username) def __str__(self): return self.user.username
class ClubListSerializer(ModelSerializer): detail = SerializerMethodField() class Meta: model = Club fields = [ 'id', 'name', 'description', 'rule', 'club_type', 'detail', 'updated', 'created', ] def get_detail(self, obj): if obj.club_type == 1: try: return GeneralClubDetailSerializer(obj.general_club).data except ObjectDoesNotExist: GeneralClub.objects.get_or_create(club=obj) return GeneralClubDetailSerializer(obj.optional_club).data elif obj.club_type == 2: try: return OptionalClubDetailSerializer(obj.optional_club).data except ObjectDoesNotExist: OptionalClub.objects.get_or_create(club=obj) return OptionalClubDetailSerializer(obj.optional_club).data elif obj.club_type == 3: try: return SpecialClubDetailSerializer(obj.special_club).data except ObjectDoesNotExist: SpecialCLub.objects.get_or_create(club=obj) return SpecialCLubDetailSerializer(obj.optional_club).data return None
class AppMetricsSerializer(ModelSerializer): beneficiaries = SerializerMethodField() user = UserSerializer(read_only=True) class Meta: model = Application fields = ('id', 'name', 'active', 'user', 'beneficiaries', 'first_active', 'last_active', 'logo_uri', 'tos_uri', 'policy_uri', 'contacts', 'website_uri', 'description') def get_beneficiaries(self, obj): distinct = AccessToken.objects.filter( application=obj.id).distinct('user').values('user') real_cnt = Crosswalk.real_objects.filter( user__in=[item['user'] for item in distinct]).values('user', '_fhir_id').count() synth_cnt = Crosswalk.synth_objects.filter( user__in=[item['user'] for item in distinct]).values('user', '_fhir_id').count() return ({'real': real_cnt, 'synthetic': synth_cnt})
class ItemsSerializer(serializers.ModelSerializer): available_stock = SerializerMethodField() class Meta: model = SoldItem fields = ( 'order', 'sku', 'quantity', 'unit_cost', 'total_cost', 'product_name', 'product_category', 'available_stock', 'tax', 'discount', ) def get_available_stock(self, obj): try: stock = ProductVariant.objects.get(sku=obj.sku) return stock.get_stock_quantity() except: return 0
class WorkflowSerializer(EdocListSerializer, TagListSerializer, NoteListSerializer, DynamicFieldsModelSerializer): step = SerializerMethodField() def get_next_step(self, current_step, step_num=1): # Recursive function to traverse through workflow steps in order # Unfortunately, this method breaks expandable fields. Hence it's always expanded # This propagates to lower levels, therefore cannot expand workflow.workflow_step.workflow_object next_step = current_step.workflow_step_parent.first() if next_step: yield from self.get_next_step(next_step, step_num=step_num+1) yield current_step, step_num def get_step(self, obj): step_nums = [] steps = [] try: top_level_step = WorkflowStep.objects.get(workflow=obj, parent__isnull=True) for step, step_num in self.get_next_step(top_level_step): step_nums.append(step_num) steps.append(step) except ObjectDoesNotExist: pass steps.reverse() step_nums.reverse() result_serializer = WorkflowStepSerializer(steps, many=True, context=self.context) return result_serializer.data class Meta: model = Workflow fields = '__all__' expandable_fields = expandable_fields['Workflow']['fields']
class UserCreateSerializer(ModelSerializer): """Serializer for only create""" token = SerializerMethodField('get_auth_token') class Meta: model = get_user_model() fields = ('email', 'password', 'token') extra_kwargs = {'password': {'write_only': True, 'min_length': 5, 'style': { 'input_type': 'password' }}} def create(self, validated_data): """Create a new user with encrypter password""" user = get_user_model().objects.create_user(**validated_data) return user def get_auth_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token
class FleetSerializer(ModelSerializer): vehicles = SerializerMethodField('get_vehicles') def get_vehicles(self, profile): fleets = Fleet.objects.filter(pk=profile.id) fleet_ids = [x.id for x in fleets] count_vehicles = Vehicle.objects.filter(fleet_id__in=fleet_ids).count() return count_vehicles class Meta: model = Fleet fields = ['id', 'name', 'identifier', 'type', 'country', 'vehicles'] def create(self, validated_data): vehicles_data = validated_data.pop('vehicles') fleet = Fleet.objects.create(**validated_data) for vehicle_data in vehicles_data: if vehicle_data.type == fleet.type: Vehicle.objects.create(fleet=fleet, **vehicle_data) else: return HttpResponse( 'Error, tipo de vehiculo erroneo segun la flota seleccionada.' ) return fleet
class TaskSerializer(ModelSerializer): class Meta: model = Task fields = ('id', 'creator', 'type', 'name', 'description', 'request_population', 'recruited_population', 'end_time', 'photo', 'edit_time', 'status') read_only_fields = ('id', 'creator') pending_read_only_fields = ('type', 'name', 'edit_time', 'status') creator = BasicUserSerializer(default=CurrentUserDefault()) recruited_population = SerializerMethodField() def __init__(self, *args, **kwargs): """If object is being updated don't allow contact to be changed.""" super().__init__(*args, **kwargs) if self.instance is not None: # Lock fields if not creating user for f in self.pending_read_only_fields: self.fields.get(f).read_only = True # self.fields.pop('parent') # or remove the field def get_recruited_population(self, obj): return TaskRequest.objects.filter(task=obj, status=1).count()
class OrderDetailSerializer(ModelSerializer): order_items = SerializerMethodField() buyer = UserDetailSerializer(read_only=True) def get_order_items(self, obj): order_number = obj.pk items = OrderItem.objects.filter(order=order_number) order = [] for item in items: order.append({ "name": item.product.name, "type": item.product.type, "price": item.product.price }) return order class Meta: model = Order fields = [ 'pk', 'buyer', 'creation_date', 'order_items', ]
class HubSerializer(ModelSerializer): editor_permission_groups = SerializerMethodField() class Meta: fields = [ 'category', 'description', 'discussion_count', 'editor_permission_groups', 'hub_image', 'id', 'is_locked', 'is_removed', 'name', 'paper_count', 'slug', 'subscriber_count', ] read_only_fields = [ 'editor_permission_groups' ] model = Hub def get_editor_permission_groups(self, hub_instance): context = self.context __context_fields = context.get( 'hub_shs_get_editor_permission_groups', {} ) editor_groups = hub_instance.editor_permission_groups return DynamicPermissionSerializer( editor_groups, **__context_fields, context=context, many=True, ).data
class UserLoginSerializer(ModelSerializer): token = CharField(read_only=True, allow_blank=True) username = CharField() remembered = BooleanField(write_only=True, required=False) password = CharField(style={'input_type': 'password'}) picture = SerializerMethodField(read_only=True) # password = PasswordField() class Meta: model = User fields = [ 'username', 'password', 'token', 'remembered', 'picture', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): return data def get_picture(self, obj): username = obj['username'] try: user = User.objects.get(username=username) user_profile = UserProfile.objects.get(user=user) try: picture = user_profile.picture.url except: picture = None return picture except User.DoesNotExist: return None except UserProfile.DoesNotExist: return None
class CoverLetterDetailSerializer(CoverLetterListSerializer): headers = SerializerMethodField() def get_headers(self, instance): headers = {} if instance.headers: parsed = email.parser.Parser().parsestr(instance.headers, True) for key in parsed.keys(): headers[key] = parsed.get_all(key) # Let's return a single string instead of a list if only one # header with this key is present if len(headers[key]) == 1: headers[key] = headers[key][0] return headers class Meta: model = CoverLetter fields = CoverLetterListSerializer.Meta.fields + ('headers', 'content') read_only_fields = fields extra_kwargs = CoverLetterListSerializer.Meta.extra_kwargs versioned_fields = CoverLetterListSerializer.Meta.versioned_fields
class StageSerializer(ModelSerializer, MetaNameSerializer): """Stage Serializer""" component = SerializerMethodField() flow_set = FlowSerializer(many=True, required=False) def get_component(self, obj: Stage) -> str: """Get object type so that we know how to edit the object""" # pyright: reportGeneralTypeIssues=false if obj.__class__ == Stage: return "" return obj.component class Meta: model = Stage fields = [ "pk", "name", "component", "verbose_name", "verbose_name_plural", "flow_set", ]
class FansSerializer(ModelSerializer): url = SerializerMethodField() headimg = SerializerMethodField() nickname = SerializerMethodField() signature = SerializerMethodField() uid = SerializerMethodField() sex = SerializerMethodField() @staticmethod def setup_eager_loading(queryset): queryset = queryset.select_related('fans') return queryset class Meta: model = Follow fields = ( # 'owner', 'url', 'uid', 'headimg', 'nickname', 'signature', 'sex', ) def get_uid(self, obj): return obj.fans.id def get_url(self, obj): # print(obj.follows.headimg) return reverse('user_public_detail', args=(obj.fans.id, )) def get_headimg(self, obj): return obj.fans.get_headimg_url() def get_nickname(self, obj): return obj.fans.nickname def get_signature(self, obj): return obj.fans.signature def get_sex(self, obj): return obj.fans.sex
class FollowSerializer(ModelSerializer): # follows = HyperlinkedRelatedField(view_name='user_detail', many=True, read_only=True) url = SerializerMethodField() headimg = SerializerMethodField() nickname = SerializerMethodField() signature = SerializerMethodField() uid = SerializerMethodField() sex = SerializerMethodField() @staticmethod def setup_eager_loading(queryset): queryset = queryset.select_related('follows') return queryset class Meta: model = Follow fields = ( 'url', 'uid', 'headimg', 'nickname', 'signature', 'sex', ) def get_uid(self, obj): return obj.follows.id def get_url(self, obj): # print(obj.follows.headimg) return reverse('user_public_detail', args=(obj.follows.id, )) def get_headimg(self, obj): return obj.follows.get_headimg_url() def get_nickname(self, obj): return obj.follows.nickname def get_signature(self, obj): return obj.follows.signature def get_sex(self, obj): return obj.follows.get_sex_display()
class ChatUserSerializer(ModelSerializer): #user = SerializerMethodField() id = SerializerMethodField() username = SerializerMethodField() first_name = SerializerMethodField() last_name = SerializerMethodField() profile = SerializerMethodField() active = SerializerMethodField() def get_id(self, obj): return obj.user.id def get_username(self, obj): return obj.user.username def get_first_name(self, obj): return obj.user.first_name def get_last_name(self, obj): return obj.user.last_name def get_profile(self, obj): return UserProfileSerializer(obj.user.profile, context={ 'request': self.context['request'] }).data def get_active(self, obj): return obj.active """ def get_user(self, obj): data = UserSerializer(obj.user).data data.update({'silenced': obj.silenced, 'blocked': obj.blocked}) return data """ class Meta: model = ChatUser fields = ('id', 'username', 'first_name', 'last_name', 'profile', 'active', 'silenced', 'blocked')
class NoteGetSerializer(ModelSerializer): """ 查看已有的笔记 """ title = SerializerMethodField() content = SerializerMethodField() isbn13 = SerializerMethodField() date = SerializerMethodField() comment = SerializerMethodField() book_img_url = SerializerMethodField() shared = SerializerMethodField() class Meta: model = Note exclude = ['user'] def get_title(self, obj): return obj.title def get_content(self, obj): return obj.content def get_isbn13(self, obj): return obj.isbn13 def get_date(self, obj): return obj.date def get_comment(self, obj): return obj.comment def get_book_img_url(self, obj): return obj.book_img_url def get_shared(self, obj): return obj.shared
class UserTestingSerializer(serializers.ModelSerializer): # user_employment = EmploymentHistorySerializer(many=True) industry = SerializerMethodField() area = SerializerMethodField() personal = SerializerMethodField() skill = SerializerMethodField() language = SerializerMethodField() education = SerializerMethodField() def get_industry(self, obj): data = industryTranslation(obj, language='fr') return data def get_area(self, obj): data = areaTranslation(obj, language='fr') return data def get_personal(self, obj): data = personalDetailTranslation(obj, language='fr') return data def get_skill(self, obj): data = skillTranslation(obj, language='fr') return data def get_language(self, obj): data = languageTranslation(obj, language='fr') return data def get_education(self, obj): data = languageTranslation(obj, language='fr') return data class Meta: model = MyUser exclude = ('password', 'last_login', 'is_superuser', 'uuid', 'is_active', 'is_staff', 'created_at', 'updated_at', 'user_permissions', 'groups', 'otp')
class MessageSerializer(ModelSerializer): user = SerializerMethodField() roomId = SerializerMethodField() timestamp = SerializerMethodField() image = SerializerMethodField() video = SerializerMethodField() has_flagged = SerializerMethodField() def get_image(self, obj): if obj.file is not None: return obj.file.get_file_url( ) if obj.file.extension in settings.IMAGE_MIME_TYPES else None return None def get_video(self, obj): if obj.file is not None: return obj.file.get_file_url( ) if obj.file.extension in settings.VIDEO_MIME_TYPES else None return None def get_timestamp(self, obj): return timestamp(obj.timestamp) def get_roomId(self, obj): return obj.room_id def get_user(self, obj): return FriendSerializer(obj.user, context={ 'request_user': self.context['request'] }).data def get_has_flagged(self, obj): return obj.has_flagged(self.context.get('request').user) class Meta: model = Message fields = ('id', 'user', 'roomId', 'content', 'image', 'video', 'timestamp', 'has_flagged')
class StatCheckSerializer(ModelSerializer): """This Serializer is implemented for statistical reasons. It provides kind of summarized information about a Check, in contrary of CheckSerializer that renders all the nested data, too.""" monster_name = SerializerMethodField() monster_picture_filename = SerializerMethodField() melody1_work_title = SerializerMethodField() melody2_work_title = SerializerMethodField() melody3_work_title = SerializerMethodField() tested_melody_work_title = SerializerMethodField() class Meta: model = Check fields = ('id', 'created_date', 'monster_name', 'monster_picture_filename', 'melody1_work_title', 'melody2_work_title', 'melody3_work_title', 'tested_melody_work_title', 'result') # ''id'' comes from the Check data # ''created_date'' comes from the Check data def get_monster_name(self, obj): return str(obj.monster.name) def get_monster_picture_filename(self, obj): return obj.monster.picture_filename def get_melody1_work_title(self, obj): return obj.game.melody1.work_title def get_melody2_work_title(self, obj): return obj.game.melody2.work_title def get_melody3_work_title(self, obj): return obj.game.melody3.work_title def get_tested_melody_work_title(self, obj): return obj.tested_melody.work_title