class AdvertisementCreateSerializer(HyperlinkedModelSerializer): author = SerializerMethodField('get_author_details') images = ImagesAssociatedAdvertisementSerializer(many=True) def get_author_details(self, obj): return UserSerializer(obj.author).data class Meta: model = Advertisement fields = ( 'id', 'title', 'main_image', 'phone_author', 'price', 'description', 'product_number', 'location_author', # 'created', # 'updated', 'author', 'images', # 'is_moderated', # 'is_visible' ) def create(self, validated_data): images_data = self.context.get('images').request.FILES advertisement = self.model.objects.create(title=validated_data.get( 'title', 'no-title'), user_id=1) # advertisement = self.model.objects.create(title=validated_data.get('title', 'no-title'), # user_id=1) for image_data in images_data.values(): AdvertisementImage.objects.create(advertisement=advertisement, image=image_data) return advertisement
class MobileAirportAssetSerializer(serializers.ModelSerializer): asset_type = MobileAssetTypeSerializer() images = AssetImageSerializer(many=True) geometry = SerializerMethodField() class Meta: model = Asset fields = "__all__" geo_field = 'geometry' def get_geometry(self, obj): if obj.geometry: return ({ "type": obj.geometry.geom_type, "coordinates": [{ 'lat': obj.geometry.x, 'lon': obj.geometry.y }] }) else: return None
class ShootingSerializer(ModelSerializer): wepon = WeponSerializer() ammo = AmmoSerializer() date_Shooting = SerializerMethodField() def get_date_Shooting(self, obj): return dateToStr(obj.date_Shooting) class Meta: model = Shooting # ordering = ['date_Shooting'] # order_by = ['-date_Shooting'] fields = ( 'id', 'wepon', 'date_Shooting', 'ammo', 'document', 'safe_number', )
class CommentListSerializer(ModelSerializer): url = HyperlinkedIdentityField(view_name='comments-api:thread', ) reply_count = SerializerMethodField() class Meta: model = Comment fields = [ 'url', 'id', # 'content_type', # 'object_id', # 'parent', 'content', 'reply_count', 'timestamp', ] def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0
class CardRevisionSerializer(HyperlinkedModelSerializer): card = PrimaryKeyRelatedField(queryset=models.Card.objects.all()) user = SerializerMethodField() def get_user(self, revision): return UserSerializer(instance=revision.user).data class Meta: model = models.CardRevision fields = ( 'card', 'created_at', 'description', 'id', 'is_archived', 'title', 'user', ) read_only_fields = ( 'id', 'user', )
class ApplicationDetailSerializer(ModelSerializer): delete_url = HyperlinkedIdentityField( view_name='apply-api:delete', lookup_field='pk', ) user = SerializerMethodField() class Meta: model = Application fields = [ 'user', 'my_location', 'payment_method', 'receipt_no', 'amount', 'date', 'delete_url' ] def get_user(self, obj): u = ('%s %s (%s)' % (obj.user.last_name, obj.user.first_name, obj.user.username )) return u
class UserSerializer(ModelSerializer): activity_periods = SerializerMethodField() id = serializers.CharField(source='user_id') real_name = serializers.CharField(source='name') tz = serializers.CharField(source='address') class Meta: model = User depth = 1 fields = ['id', 'real_name', 'tz', 'activity_periods'] def get_activity_periods(self, user): ''' gets the pending appointments for the given clinician ''' context = [] use = user.activity_user.all() for us in use: x = {} x['start_time'] = us.start_time.strftime('%b %d %Y %I:%M %p') x['end_time'] = us.end_time.strftime('%b %d %Y %I:%M %p') context.append(x) return context
class UserLoginSerializer(ModelSerializer): id = SerializerMethodField() token = CharField(allow_blank=True, read_only=True) username = CharField() email = EmailField(label='Email Address') class Meta: model = User fields = [ 'username', 'email', 'password', 'token', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # email = data['email'] # user_qs = User.objects.filter(email=email) # if user_qs.exists(): # raise ValidationError("This user has already registered.") return data
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', 'url', 'name', 'title', 'filetype', 'publisher', 'source_url', 'iati_version', 'added_manually', ) def get_type(self, obj): return obj.get_filetype_display()
class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = [ 'id', 'first_name', 'last_name', 'email', 'type', 'date_joined', 'dark_mode' ] id = CharField(source='user.id', read_only=True) first_name = CharField(source='user.first_name', read_only=True) last_name = CharField(source='user.last_name', read_only=True) email = EmailField(source='user.email', read_only=True) date_joined = DateTimeField(source='user.date_joined', read_only=True) type = SerializerMethodField() def get_type(self, profile): user = profile.user if user.is_superuser: return 'admin' if user.is_staff: return 'teacher' return 'student'
class AnnotationSerializer(ModelSerializer): verified_by_user = SerializerMethodField('is_verified_by_user') def is_verified_by_user(self, annotation): user = self.context['request'].user return Verification.objects.filter(user=user, annotation=annotation).exists() class Meta: model = Annotation fields = ( 'annotation_type', 'id', 'vector', 'verified_by_user', 'image', 'concealed', 'blurred', ) annotation_type = AnnotationTypeSerializer(read_only=True) image = ImageSerializer(read_only=True)
class TechnologyDeleteSerializer(ModelSerializer): image = SerializerMethodField() class Meta: model = Technology fields = [ 'id', 'title', 'slug', 'detail', 'image', 'doc_url', 'logo', 'logo_url', ] def get_image(self, obj): try: image = obj.logo.url except: image = None return image
class NoteSerializer(DocumentSerializer): links = SerializerMethodField() comments = CommentSerializer(many=True) tags = TagSerializer(many=True) class Meta: model = Note def create(self, validated_data): tags = validated_data.pop('tags') new_note = Note(**validated_data) new_note.tags.extend([(Tag(**tag_data)) for tag_data in tags]) new_note.save() return new_note def update(self, instance, validated_data): tags = validated_data.pop('tags') comments = validated_data.pop('comments') updated_instance = super(NoteSerializer, self).update( instance, validated_data) tags = [(Tag(**tag_data)) for tag_data in tags] updated_instance.update(tags=tags, comments=comments) return updated_instance def get_links(self, obj): request = self.context['request'] return { "self": reverse( 'note-detail', kwargs={'id': obj.id}, request=request) }
class PostSerializer(serializers.ModelSerializer): # url=HyperlinkedIdentityField( # view_name='post-api:detail', # lookup_field='pk' # ) user = SerializerMethodField() class Meta: model = post fields = [ 'id', 'user', 'title', 'content', 'image', 'views', 'pin', 'pub_date' ] def get_user(self, obj): return str(obj.user.username) def get_image(self, obj): try: return obj.image.url except: return None
class CommentListSerializer(ModelSerializer): reply_count = SerializerMethodField(read_only=True) user = UserDetailSerializer() url = comment_url # post = post_url class Meta: model = Comment fields = [ 'id', 'user', 'url', 'timestamp', 'reply_count', 'content', ] def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() else: return 0
class LearnerViewProfileSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) certificates_count = SerializerMethodField('_certificates_count') def _certificates_count(self, obj): return obj.user.certificate_set.all().filter(granted_to_type=1).count() class Meta: model = Profile fields = ( 'user', 'full_name', 'learner_position', 'learner_specialisation', 'learner_about', 'public_profile', 'learner_site', 'phone_number', 'learner_country', 'learner_avatar', 'certificates_count', )
class PostListSerializer(ModelSerializer): url = post_detail_url author = SerializerMethodField() class Meta: model = Post fields = [ 'url', 'id', 'author', 'title', 'slug', 'content', 'meta_description', 'keywords', 'categories', 'tags', 'publish', ] def get_author(self, obj): return str(obj.author)
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 will 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 to be serialized choices = SerializerMethodField() #serialize choices #declare attribute function def get_choices(self,obj): choices = obj.choice_set.all() return ChoiceSerializer(choices, many=True).data #declare meta class class Meta: model = Question fields = ('id', 'text', 'pub_date', 'choices')
class CommentListSerializer(ModelSerializer): url = HyperlinkedIdentityField( view_name ="comments-api:thread", ) reply_count = SerializerMethodField() class Meta: model = Comment fields = [ "url", "id", # "content_type", # "object_id", # "parent", "content", "reply_count", "timestamp", ] def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0
class ArticleSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='articles-api:detail', lookup_field='slug') image = SerializerMethodField() class Meta: model = Article fields = [ 'id', 'url', 'title', 'slug', 'date', 'image', ] def get_image(self, obj): try: image = obj.thumb.url except: image = None return image
class CommentListSerializer(ModelSerializer): reply_count = SerializerMethodField() url = HyperlinkedIdentityField(view_name='comments-api:detail', lookup_field='id') class Meta: model = Comment fields = [ 'id', 'url', 'content_type', 'object_id', 'parent', 'content', 'reply_count', ] def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0
class NoteForListSerializer(NoteSerializer): obj_meta = SerializerMethodField() def get_obj_meta(self, note): # grep: comm-content-type. obj = note.thread.obj if obj.__class__ == Webapp: return { 'icon': obj.get_icon_url(64), 'name': unicode(obj.name), 'slug': obj.app_slug } else: return { 'icon': obj.get_icon_url(64), 'name': unicode(obj.name), 'slug': obj.slug } class Meta(NoteSerializer.Meta): fields = ('id', 'created', 'attachments', 'author', 'author_meta', 'body', 'note_type', 'obj_meta', 'thread')
class GroupListSerializer(ModelSerializer): # my_posts = PostListSerializer(many=True, read_only=True) my_posts = SerializerMethodField() group = PostListSerializer(many=True, read_only=True) #### YOU CAN USE BELLOW LINKS TOO ### # group = StringRelatedField(many=True) # group = PrimaryKeyRelatedField(many=True, read_only=True) # group = HyperlinkedRelatedField(many=True, read_only=True, view_name='blog-api:post-detail', lookup_field='id') # group = SlugRelatedField(many=True, read_only=True, slug_field='title') class Meta: model = BlogGroup fields = ('id', 'title', 'my_posts', 'group') def get_my_posts(self, obj): # a = PostListSerializer(Blog.objects.all(), many=True, read_only=True, context={'request': self.context}) # print obj.objects.all() # return PostListSerializer(many=True, read_only=True).data return 1
class DocSerializer(ModelSerializer): download_url = SerializerMethodField() class Meta: model = Document fields = ( "id", "title", "download_url", "higher_level_docs", "same_level_docs", "lower_level_docs", "import_batch", "metadata_id", ) def get_download_url(self, doc): request = self.context.get("request", None) if request is None or not doc.file or not doc.file.file: return None return request.build_absolute_uri(doc.download_url)
class KanbanColumnSerializer(HyperlinkedModelSerializer): cards = SerializerMethodField() project = PrimaryKeyRelatedField(queryset=models.Project.objects.all()) def get_cards(self, column): if isinstance(column, OrderedDict): column = column.get('id') queryset = models.Card.objects.filter(kanban_column=column, is_archived=False) serializer = CardSerializer(instance=queryset, many=True) return serializer.data class Meta: model = models.KanbanColumn fields = ( 'cards', 'id', 'order', 'project', 'title', ) read_only_fields = ( 'id', ) def create(self, data): kanban_column = self.fill(models.KanbanColumn(), data) kanban_column.save() return kanban_column def fill(self, kanban_column, data): kanban_column.order = data.get('order') kanban_column.project = data.get('project') kanban_column.title = data.get('title') return kanban_column def update(self, kanban_column, data): kanban_column = self.fill(kanban_column, data) kanban_column.save() return kanban_column
class ReviewSerializer(ModelSerializer): submission = SlugRelatedField(slug_field='code', read_only=True) user = SlugRelatedField(slug_field='name', read_only=True) answers = SerializerMethodField() def get_answers(self, obj): return AnswerSerializer(Answer.objects.filter(review=obj), many=True).data class Meta: model = Review fields = ( 'id', 'answers', 'submission', 'user', 'text', 'score', 'override_vote', 'created', 'updated', )
class PostListSerializer(ModelSerializer): user = UserDetailSerializer(read_only=True) url = HyperlinkedIdentityField(view_name='posts-api:detail', lookup_field='slug') delete_url = HyperlinkedIdentityField(view_name='posts-api:delete', lookup_field='slug') user = SerializerMethodField() class Meta: model = Post fields = [ 'url', 'user', 'id', 'title', # 'slug', 'content', 'delete_url' ] def get_user(self, obj): return str(obj.user.username)
class BagBaseSr(ModelSerializer): area_uid = SerializerMethodField() class Meta: model = Bag exclude = () read_only_fields = ('id', ) uid = CharField( validators=[ UniqueValidator( queryset=Bag.objects.all(), message="Duplicate bill of landing code", ) ], required=False, ) def get_area_uid(self, obj): if not obj.area: return '' return obj.area.uid
class TeamCreateSerializer(ModelSerializer): created_at = UnixEpochDateTimeField(read_only=True) flag = SerializerMethodField() country = EmptyCountryField(allow_blank=True) def get_flag(self, obj): return obj.country.flag def validate(self, data): game = get_game() error_dict = {} if 'is_school' in data and data['is_school']: if 'school_name' not in data or not data['school_name'].strip(): error_dict['school_name'] = [_('The field is required for school teams')] if 'teacher_name' not in data or not data['teacher_name'].strip(): error_dict['teacher_name'] = [_('The field is required for school teams')] if game.send_emails \ and ('teacher_email' not in data \ or not data['teacher_email'].strip()): error_dict['teacher_email'] = [_('The field is required for school teams')] if 'address' not in data or not data['address'].strip(): error_dict['address'] = [_('The field is required for school teams')] if game.send_emails \ and ('leader_email' not in data \ or not data['leader_email'].strip()): error_dict['leader_email'] = [_('The field is required for the game')] if len(error_dict) > 0: raise ValidationError(error_dict) return data class Meta: model = Team exclude = ('id',) read_only_fields = ('created_at', 'auth_string') write_only_fields = ('teacher_name', 'teacher_email', 'leader_email', 'address')
class PoodleBaseSerializer(ModelSerializer): lookup_field = "slug" url = SerializerMethodField() color_text = CharField(source='color.text', default='Unknown') origin_country_text = CharField(source='origin_country.text', default='Unknown') origin_country_code = CharField(source='origin_country.code', default='UNK') sire = CharField(source='sire.name_registered', default='--') dam = CharField(source='dam.name_registered', default='--') class Meta: model = Poodle fields = [ 'slug', 'url', 'id', 'name_call', 'name_registered', 'color_text', 'origin_country_code', 'sire', 'dam', 'origin_country_text', 'dob', 'sex', ] read_only_fields = [ 'origin_country_code', 'origin_country_text', 'color_text', 'dob_dod', 'sire', 'dam' ] def get_url(self, pood): """Return full API URL for serialized POST object""" return reverse( "core:poodle-detail", kwargs=dict(slug=pood.slug), request=self.context["request"], )