コード例 #1
0
class EntrySerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(EntrySerializer, self).__init__(*args, **kwargs)
        # to make testing more concise we'll only output the
        # `featured` field when it's requested via `include`
        request = kwargs.get('context', {}).get('request')
        if request and 'featured' not in request.query_params.get(
                'include', []):
            self.fields.pop('featured', None)

    included_serializers = {
        'authors': 'example.serializers.AuthorSerializer',
        'comments': 'example.serializers.CommentSerializer',
        'featured': 'example.serializers.EntrySerializer',
        'suggested': 'example.serializers.EntrySerializer',
        'tags': 'example.serializers.TaggedItemSerializer',
    }

    body_format = serializers.SerializerMethodField()
    # many related from model
    comments = relations.ResourceRelatedField(many=True, read_only=True)
    # many related from serializer
    suggested = relations.SerializerMethodResourceRelatedField(
        source='get_suggested',
        model=Entry,
        many=True,
        read_only=True,
        related_link_view_name='entry-suggested',
        related_link_url_kwarg='entry_pk',
        self_link_view_name='entry-relationships',
    )
    # single related from serializer
    featured = relations.SerializerMethodResourceRelatedField(
        source='get_featured', model=Entry, read_only=True)
    tags = TaggedItemSerializer(many=True, read_only=True)

    def get_suggested(self, obj):
        return Entry.objects.exclude(pk=obj.pk)

    def get_featured(self, obj):
        return Entry.objects.exclude(pk=obj.pk).first()

    def get_body_format(self, obj):
        return 'text'

    class Meta:
        model = Entry
        fields = ('blog', 'headline', 'body_text', 'pub_date', 'mod_date',
                  'authors', 'comments', 'featured', 'suggested', 'tags')
        read_only_fields = ('tags', )
        meta_fields = ('body_format', )

    class JSONAPIMeta:
        included_resources = ['comments']
コード例 #2
0
ファイル: serializers.py プロジェクト: hairmare/timed-backend
class UserAbsenceTypeSerializer(ModelSerializer):
    """Absence type serializer for a user.

    This is only a simulated relation to the user to show the absence credits
    and balances.
    """

    credit = IntegerField()
    used_days = IntegerField()
    used_duration = DurationField()
    balance = IntegerField()

    user = relations.SerializerMethodResourceRelatedField(
        source='get_user', model=get_user_model(), read_only=True)

    absence_credits = relations.SerializerMethodResourceRelatedField(
        source='get_absence_credits',
        model=models.AbsenceCredit,
        many=True,
        read_only=True)

    def get_user(self, instance):
        return get_user_model().objects.get(pk=instance.user_id)

    def get_absence_credits(self, instance):
        """Get the absence credits for the user and type."""
        return models.AbsenceCredit.objects.filter(
            absence_type=instance,
            user__id=instance.user_id,
            date__gte=instance.start_date,
            date__lte=instance.end_date)

    included_serializers = {
        'absence_credits':
        'timed.employment.serializers.AbsenceCreditSerializer',
    }

    class Meta:
        """Meta information for the absence type serializer."""

        model = models.UserAbsenceType
        fields = [
            'name',
            'fill_worktime',
            'credit',
            'used_duration',
            'used_days',
            'balance',
            'absence_credits',
            'user',
        ]
コード例 #3
0
class AuthorSerializer(serializers.ModelSerializer):
    bio = relations.ResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        queryset=AuthorBio.objects,
    )
    entries = relations.ResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        queryset=Entry.objects,
        many=True)
    first_entry = relations.SerializerMethodResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        model=Entry,
        read_only=True,
        source='get_first_entry')
    included_serializers = {
        'bio': AuthorBioSerializer,
        'type': AuthorTypeSerializer
    }
    related_serializers = {
        'bio': 'example.serializers.AuthorBioSerializer',
        'entries': 'example.serializers.EntrySerializer',
        'first_entry': 'example.serializers.EntrySerializer'
    }

    class Meta:
        model = Author
        fields = ('name', 'email', 'bio', 'entries', 'first_entry', 'type')

    def get_first_entry(self, obj):
        return obj.entries.first()
コード例 #4
0
class AuthorSerializer(serializers.ModelSerializer):
    bio = relations.ResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        queryset=AuthorBio.objects,
    )
    entries = relations.ResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        queryset=Entry.objects,
        many=True)
    first_entry = relations.SerializerMethodResourceRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        model=Entry,
    )
    comments = relations.HyperlinkedRelatedField(
        related_link_view_name='author-related',
        self_link_view_name='author-relationships',
        queryset=Comment.objects,
        many=True)
    secrets = serializers.HiddenField(default='Shhhh!')
    defaults = serializers.CharField(
        default='default',
        max_length=20,
        min_length=3,
        write_only=True,
        help_text='help for defaults',
    )
    included_serializers = {
        'bio': AuthorBioSerializer,
        'type': AuthorTypeSerializer
    }
    related_serializers = {
        'bio': 'example.serializers.AuthorBioSerializer',
        'type': 'example.serializers.AuthorTypeSerializer',
        'comments': 'example.serializers.CommentSerializer',
        'entries': 'example.serializers.EntrySerializer',
        'first_entry': 'example.serializers.EntrySerializer'
    }

    class Meta:
        model = Author
        fields = ('name', 'email', 'bio', 'entries', 'comments', 'first_entry',
                  'type', 'secrets', 'defaults')

    def get_first_entry(self, obj):
        return obj.entries.first()
コード例 #5
0
class EntrySerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        # to make testing more concise we'll only output the
        # `suggested` field when it's requested via `include`
        request = kwargs.get('context', {}).get('request')
        if request and 'suggested' not in request.query_params.get(
                'include', []):
            self.fields.pop('suggested')
        super(EntrySerializer, self).__init__(*args, **kwargs)

    included_serializers = {
        'comments': 'example.serializers.CommentSerializer',
        'suggested': 'example.serializers.EntrySerializer',
    }

    body_format = serializers.SerializerMethodField()
    comments = relations.ResourceRelatedField(source='comment_set',
                                              many=True,
                                              read_only=True)
    suggested = relations.SerializerMethodResourceRelatedField(
        source='get_suggested', model=Entry, read_only=True)

    def get_suggested(self, obj):
        return Entry.objects.exclude(pk=obj.pk).first()

    def get_body_format(self, obj):
        return 'text'

    class Meta:
        model = Entry
        fields = (
            'blog',
            'headline',
            'body_text',
            'pub_date',
            'mod_date',
            'authors',
            'comments',
            'suggested',
        )
        meta_fields = ('body_format', )
コード例 #6
0
class ReportIntersectionSerializer(Serializer):
    """
    Serializer of report intersections.

    Serializes a representation of all fields which are the same
    in given Report objects. If values of one field are not the same
    in all objects it will be represented as None.

    Serializer expect instance to have a queryset value.
    """

    customer = relations.SerializerMethodResourceRelatedField(
        source="get_customer", model=Customer, read_only=True)
    project = relations.SerializerMethodResourceRelatedField(
        source="get_project", model=Project, read_only=True)
    task = relations.SerializerMethodResourceRelatedField(source="get_task",
                                                          model=Task,
                                                          read_only=True)
    comment = SerializerMethodField()
    review = SerializerMethodField()
    not_billable = SerializerMethodField()
    billed = SerializerMethodField()
    verified = SerializerMethodField()

    def _intersection(self, instance, field, model=None):
        """Get intersection of given field.

        :return: Returns value of field if objects have same value;
                 otherwise None
        """
        value = None
        queryset = instance["queryset"]
        values = queryset.values(field).distinct()
        if values.count() == 1:
            value = values.first()[field]
            if model:
                value = model.objects.get(pk=value)

        return value

    def get_customer(self, instance):
        return self._intersection(instance, "task__project__customer",
                                  Customer)

    def get_project(self, instance):
        return self._intersection(instance, "task__project", Project)

    def get_task(self, instance):
        return self._intersection(instance, "task", Task)

    def get_comment(self, instance):
        return self._intersection(instance, "comment")

    def get_review(self, instance):
        return self._intersection(instance, "review")

    def get_not_billable(self, instance):
        return self._intersection(instance, "not_billable")

    def get_billed(self, instance):
        return self._intersection(instance, "billed")

    def get_verified(self, instance):
        queryset = instance["queryset"]
        queryset = queryset.annotate(verified=Case(
            When(verified_by_id__isnull=True, then=False),
            default=True,
            output_field=BooleanField(),
        ))
        instance["queryset"] = queryset
        return self._intersection(instance, "verified")

    def get_root_meta(self, resource, many):
        """Add number of results to meta."""
        queryset = self.instance["queryset"]
        return {"count": queryset.count()}

    included_serializers = {
        "customer": "timed.projects.serializers.CustomerSerializer",
        "project": "timed.projects.serializers.ProjectSerializer",
        "task": "timed.projects.serializers.TaskSerializer",
    }

    class Meta:
        resource_name = "report-intersections"
コード例 #7
0
class AbsenceBalanceSerializer(Serializer):
    credit = SerializerMethodField()
    used_days = SerializerMethodField()
    used_duration = SerializerMethodField()
    balance = SerializerMethodField()

    user = relations.ResourceRelatedField(model=get_user_model(),
                                          read_only=True)

    absence_type = relations.ResourceRelatedField(model=models.AbsenceType,
                                                  read_only=True,
                                                  source="id")

    absence_credits = relations.SerializerMethodResourceRelatedField(
        source="get_absence_credits",
        model=models.AbsenceCredit,
        many=True,
        read_only=True,
    )

    def _get_start(self, instance):
        return date(instance.date.year, 1, 1)

    def get_credit(self, instance):
        """
        Calculate how many days are approved for given absence type.

        For absence types which fill worktime this will be None.
        """
        if "credit" in instance:
            return instance["credit"]

        # id is mapped to absence type
        absence_type = instance.id

        start = self._get_start(instance)

        # avoid multiple calculations as get_balance needs it as well
        instance["credit"] = absence_type.calculate_credit(
            instance.user, start, instance.date)
        return instance["credit"]

    def get_used_days(self, instance):
        """
        Calculate how many days are used of given absence type.

        For absence types which fill worktime this will be None.
        """
        if "used_days" in instance:
            return instance["used_days"]

        # id is mapped to absence type
        absence_type = instance.id

        start = self._get_start(instance)

        # avoid multiple calculations as get_balance needs it as well
        instance["used_days"] = absence_type.calculate_used_days(
            instance.user, start, instance.date)
        return instance["used_days"]

    def get_used_duration(self, instance):
        """
        Calculate duration of absence type.

        For absence types which fill worktime this will be None.
        """
        # id is mapped to absence type
        absence_type = instance.id
        if not absence_type.fill_worktime:
            return None

        start = self._get_start(instance)
        absences = sum(
            [
                absence.calculate_duration(
                    models.Employment.objects.get_at(instance.user,
                                                     absence.date))
                for absence in Absence.objects.filter(
                    user=instance.user,
                    date__range=[start, instance.date],
                    type_id=instance.id,
                ).select_related("type")
            ],
            timedelta(),
        )
        return duration_string(absences)

    def get_absence_credits(self, instance):
        """Get the absence credits for the user and type."""
        if "absence_credits" in instance:
            return instance["absence_credits"]

        # id is mapped to absence type
        absence_type = instance.id

        start = self._get_start(instance)
        absence_credits = models.AbsenceCredit.objects.filter(
            absence_type=absence_type,
            user=instance.user,
            date__range=[start, instance.date],
        ).select_related("user")

        # avoid multiple calculations when absence credits need to be included
        instance["absence_credits"] = absence_credits

        return absence_credits

    def get_balance(self, instance):
        # id is mapped to absence type
        absence_type = instance.id
        if absence_type.fill_worktime:
            return None

        return self.get_credit(instance) - self.get_used_days(instance)

    included_serializers = {
        "absence_type": "timed.employment.serializers.AbsenceTypeSerializer",
        "absence_credits":
        "timed.employment.serializers.AbsenceCreditSerializer",
    }

    class Meta:
        resource_name = "absence-balances"
コード例 #8
0
class EntrySerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(EntrySerializer, self).__init__(*args, **kwargs)
        # to make testing more concise we'll only output the
        # `featured` field when it's requested via `include`
        request = kwargs.get("context", {}).get("request")
        if request and "featured" not in request.query_params.get("include", []):
            self.fields.pop("featured", None)

    included_serializers = {
        "authors": "example.serializers.AuthorSerializer",
        "comments": "example.serializers.CommentSerializer",
        "featured": "example.serializers.EntrySerializer",
        "suggested": "example.serializers.EntrySerializer",
        "tags": "example.serializers.TaggedItemSerializer",
    }

    body_format = serializers.SerializerMethodField()
    # single related from model
    blog_hyperlinked = relations.HyperlinkedRelatedField(
        related_link_view_name="entry-blog",
        related_link_url_kwarg="entry_pk",
        self_link_view_name="entry-relationships",
        read_only=True,
        source="blog",
    )
    # many related from model
    comments = relations.ResourceRelatedField(many=True, read_only=True)
    # many related hyperlinked from model
    comments_hyperlinked = relations.HyperlinkedRelatedField(
        related_link_view_name="entry-comments",
        related_link_url_kwarg="entry_pk",
        self_link_view_name="entry-relationships",
        many=True,
        read_only=True,
        source="comments",
    )
    # many related from serializer
    suggested = relations.SerializerMethodResourceRelatedField(
        related_link_view_name="entry-suggested",
        related_link_url_kwarg="entry_pk",
        self_link_view_name="entry-relationships",
        model=Entry,
        many=True,
    )
    # many related hyperlinked from serializer
    suggested_hyperlinked = relations.SerializerMethodHyperlinkedRelatedField(
        related_link_view_name="entry-suggested",
        related_link_url_kwarg="entry_pk",
        self_link_view_name="entry-relationships",
        model=Entry,
        many=True,
    )
    # single related from serializer
    featured = relations.SerializerMethodResourceRelatedField(model=Entry)
    # single related hyperlinked from serializer
    featured_hyperlinked = relations.SerializerMethodHyperlinkedRelatedField(
        related_link_view_name="entry-featured",
        related_link_url_kwarg="entry_pk",
        self_link_view_name="entry-relationships",
        model=Entry,
        read_only=True,
    )
    tags = relations.ResourceRelatedField(many=True, read_only=True)

    def get_suggested(self, obj):
        return Entry.objects.exclude(pk=obj.pk)

    def get_featured(self, obj):
        return Entry.objects.exclude(pk=obj.pk).first()

    def get_body_format(self, obj):
        return "text"

    class Meta:
        model = Entry
        fields = (
            "blog",
            "blog_hyperlinked",
            "headline",
            "body_text",
            "pub_date",
            "mod_date",
            "authors",
            "comments",
            "comments_hyperlinked",
            "featured",
            "suggested",
            "suggested_hyperlinked",
            "tags",
            "featured_hyperlinked",
        )
        read_only_fields = ("tags",)
        meta_fields = ("body_format",)

    class JSONAPIMeta:
        included_resources = ["comments"]
コード例 #9
0
class AuthorSerializer(serializers.ModelSerializer):
    bio = relations.ResourceRelatedField(
        related_link_view_name="author-related",
        self_link_view_name="author-relationships",
        queryset=AuthorBio.objects,
    )
    entries = relations.ResourceRelatedField(
        related_link_view_name="author-related",
        self_link_view_name="author-relationships",
        queryset=Entry.objects,
        many=True,
    )
    first_entry = relations.SerializerMethodResourceRelatedField(
        related_link_view_name="author-related",
        self_link_view_name="author-relationships",
        model=Entry,
    )
    comments = relations.HyperlinkedRelatedField(
        related_link_view_name="author-related",
        self_link_view_name="author-relationships",
        queryset=Comment.objects,
        many=True,
    )
    secrets = serializers.HiddenField(default="Shhhh!")
    defaults = serializers.CharField(
        default="default",
        max_length=20,
        min_length=3,
        write_only=True,
        help_text="help for defaults",
    )
    initials = serializers.SerializerMethodField()
    included_serializers = {"bio": AuthorBioSerializer, "type": AuthorTypeSerializer}
    related_serializers = {
        "bio": "example.serializers.AuthorBioSerializer",
        "type": "example.serializers.AuthorTypeSerializer",
        "comments": "example.serializers.CommentSerializer",
        "entries": "example.serializers.EntrySerializer",
        "first_entry": "example.serializers.EntrySerializer",
    }

    class Meta:
        model = Author
        fields = (
            "name",
            "email",
            "bio",
            "entries",
            "comments",
            "first_entry",
            "type",
            "secrets",
            "defaults",
            "initials",
        )
        meta_fields = ("initials",)

    def get_first_entry(self, obj):
        return obj.entries.first()

    def get_initials(self, obj):
        return "".join([word[0] for word in obj.name.split(" ")])
コード例 #10
0
        'int32'


class ProjectWithCustomIDAndExtraProperties(ProjectWithCustomID):
    @property
    def one_member(self):
        return

    @property
    def many_members(self):
        return


@pytest.mark.parametrize(
    'serializer_field,expect_array', (
        (relations.SerializerMethodResourceRelatedField(model=MemberWithCustomID, source='get_member', read_only=True),
         False),
        (relations.SerializerMethodResourceRelatedField(model=MemberWithCustomID, source='get_members', read_only=True,
                                                        many=True),
         True),
        (relations.ResourceRelatedField(model=MemberWithCustomID, source='one_member', read_only=True),
         False),
        (relations.ResourceRelatedField(model=MemberWithCustomID, source='many_members', read_only=True, many=True),
         True),
        (relations.ResourceRelatedField(queryset=MemberWithCustomID.objects.all(), source='one_member'),
         False),
        (relations.ResourceRelatedField(queryset=MemberWithCustomID.objects.all(), source='many_members', many=True),
         True),
    )
)
def test_get__manual_related_resource(serializer_field, expect_array):
コード例 #11
0
ファイル: serializers.py プロジェクト: hairmare/timed-backend
class UserSerializer(ModelSerializer):
    """User serializer."""

    employments = relations.ResourceRelatedField(many=True, read_only=True)
    worktime_balance = SerializerMethodField()
    user_absence_types = relations.SerializerMethodResourceRelatedField(
        source='get_user_absence_types',
        model=models.UserAbsenceType,
        many=True,
        read_only=True)

    def get_user_absence_types(self, instance):
        """Get the user absence types for this user.

        :returns: All absence types for this user
        """
        request = self.context.get('request')

        end = datetime.strptime(
            request.query_params.get('until',
                                     date.today().strftime('%Y-%m-%d')),
            '%Y-%m-%d').date()

        try:
            employment = models.Employment.objects.for_user(instance, end)
        except models.Employment.DoesNotExist:
            return models.UserAbsenceType.objects.none()

        start = max(employment.start_date, date(date.today().year, 1, 1))

        return models.UserAbsenceType.objects.with_user(instance, start, end)

    def get_worktime(self, user, start=None, end=None):
        """Calculate the reported, expected and balance for user.

        1.  Determine the current employment of the user
        2.  Take the latest of those two as start date:
             * The start of the year
             * The start of the current employment
        3.  Take the delivered date if given or the current date as end date
        4.  Determine the count of workdays within start and end date
        5.  Determine the count of public holidays within start and end date
        6.  The expected worktime consists of following elements:
             * Workdays
             * Subtracted by holidays
             * Multiplicated with the worktime per day of the employment
        7.  Determine the overtime credit duration within start and end date
        8.  The reported worktime is the sum of the durations of all reports
            for this user within start and end date
        9.  The absences are all absences for this user between the start and
            end time
        10. The balance is the reported time plus the absences plus the
            overtime credit minus the expected worktime

        :param user:       user to get worktime from
        :param start_date: worktime starting on  given day;
                           if not set when employment started resp. begining of
                           the year
        :param end_date:   worktime till day or if not set today
        :returns: tuple of 3 values reported, expected and balance in given
                  time frame
        """
        end = end or date.today()

        try:
            employment = models.Employment.objects.for_user(user, end)
        except models.Employment.DoesNotExist:
            # If there is no active employment, set the balance to 0
            return timedelta(), timedelta(), timedelta()

        location = employment.location

        if start is None:
            start = max(employment.start_date, date(date.today().year, 1, 1))

        # workdays is in isoweekday, byweekday expects Monday to be zero
        week_workdays = [int(day) - 1 for day in employment.location.workdays]
        workdays = rrule.rrule(rrule.DAILY,
                               dtstart=start,
                               until=end,
                               byweekday=week_workdays).count()

        # converting workdays as db expects 1 (Sunday) to 7 (Saturday)
        workdays_db = [
            # special case for Sunday
            int(day) == 7 and 1 or int(day) + 1 for day in location.workdays
        ]
        holidays = models.PublicHoliday.objects.filter(
            location=location,
            date__gte=start,
            date__lte=end,
            date__week_day__in=workdays_db).count()

        expected_worktime = employment.worktime_per_day * (workdays - holidays)

        overtime_credit = sum(
            models.OvertimeCredit.objects.filter(user=user,
                                                 date__gte=start,
                                                 date__lte=end).values_list(
                                                     'duration', flat=True),
            timedelta())

        reported_worktime = sum(
            Report.objects.filter(user=user, date__gte=start,
                                  date__lte=end).values_list('duration',
                                                             flat=True),
            timedelta())

        absences = sum(
            Absence.objects.filter(user=user, date__gte=start,
                                   date__lte=end).values_list('duration',
                                                              flat=True),
            timedelta())

        reported = reported_worktime + absences + overtime_credit

        return (reported, expected_worktime, reported - expected_worktime)

    def get_worktime_balance(self, instance):
        """Format the worktime balance.

        :return: The formatted worktime balance.
        :rtype:  str
        """
        request = self.context.get('request')
        until = request.query_params.get('until')
        end_date = until and datetime.strptime(until, '%Y-%m-%d').date()

        _, _, balance = self.get_worktime(instance, None, end_date)
        return duration_string(balance)

    included_serializers = {
        'employments':
        'timed.employment.serializers.EmploymentSerializer',
        'user_absence_types':
        'timed.employment.serializers.UserAbsenceTypeSerializer'
    }

    class Meta:
        """Meta information for the user serializer."""

        model = get_user_model()
        fields = [
            'username',
            'first_name',
            'last_name',
            'email',
            'employments',
            'worktime_balance',
            'is_staff',
            'is_active',
            'user_absence_types',
        ]
コード例 #12
0
ファイル: serializers.py プロジェクト: kaigezhang/xsio
class ProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source='user.username')
    bio = serializers.CharField(allow_blank=True, required=False)
    image = serializers.SerializerMethodField()
    following = serializers.SerializerMethodField()

    # followings = relations.ResourceRelatedField(many=True, read_only=True)
    # followers = relations.ResourceRelatedField(many=True, read_only=True)
    collects = relations.ResourceRelatedField(many=True, read_only=True)
    favorites = relations.ResourceRelatedField(many=True, read_only=True)
    owns = relations.ResourceRelatedField(many=True, read_only=True)

    followings = relations.SerializerMethodResourceRelatedField(
        source='get_followings',
        read_only=True,
        model=Profile,
    )
    followers = relations.SerializerMethodResourceRelatedField(
        source='get_followers',
        read_only=True,
        model=Profile,
    )

    related_serializers = {
        'followings': 'scholar.apps.profiles.serializers.ProfileSerializer',
        'followers': 'scholar.apps.profiles.serializers.ProfileSerializer',
        'collects': 'scholar.apps.posts.serializers.PostSerializer',
        'favorites':
        'scholar.apps.annotations.serializers.annotationSerializer',
        'owns': 'scholar.apps.papers.serializers.FileSerializer',
    }

    class Meta:
        model = Profile
        fields = (
            'user',
            'username',
            'bio',
            'image',
            'following',
            'followers',
            'followings',
            'collects',
            'favorites',
            'owns',
        )
        read_only_fields = (
            'user',
            'username',
            'collects',
            'favorites',
            'owns',
            'followers',
            'followings',
        )

    def get_image(self, obj):
        if obj.image:
            return obj.image
        return 'https://static.productionready.io/images/smiley-cyrus.jpg'

    def get_following(self, instance):
        request = self.context.get('request', None)
        if request is None:
            return False
        if not request.user.is_authenticated():
            return False

        follower = request.user.profile
        followee = instance
        return follower.is_following(followee)

    def get_followings(self, instance):
        return instance.follows.all()

    def get_followers(self, instance):
        return instance.followed_by.all()
コード例 #13
0
ファイル: serializers.py プロジェクト: kaigezhang/xsio
class PostSerializer(serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super(PostSerializer, self).__init__(*args, **kwargs)
        request = kwargs.get('context', {}).get('request')
        if request and 'featured' not in request.query_params.get('include', []):
            self.fields.pop('featured', None)

    include_serializers = {
        'comments': 'scholar.apps.posts.serializers.CommentSerializer',
        'featured': 'scholar.apps.posts.serializers.PostSerializer',
        'suggested': 'scholar.apps.posts.serializers.PostSerializer',
        'tags': 'scholar.apps.posts.serializers.TagSerializer',
    }
    author = ProfileSerializer(read_only=True)
    body_text = serializers.CharField(required=False)

    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name='get_favorites_count'
    )

    tags = TagSerializer(
        many=True, read_only=True
    )
    comments = CommentSerializer(
        many=True, read_only=True
    )

    suggested = relations.SerializerMethodResourceRelatedField(
        source='get_suggested',
        model=Post,
        many=True,
        read_only=True,
        related_link_view_name='post-suggested',
        related_link_url_kwarg='post_pk',
        # self_link_view_name='post-relationships',
    )

    featured = relations.SerializerMethodResourceRelatedField(
        source='get_featured',
        model=Post,
        read_only=True
    )

    def get_suggested(self, obj):
        return Post.objects.exclude(pk=obj.pk)

    def get_featured(self, obj):
        return Post.objects.exclude(pk=obj.pk).first()

    def get_favorites_count(self, obj):
        pass

    class Meta:
        model = Post
        fields = (
            'body_text',
            'author',
            'comments',
            'tags',
            'featured',
            'suggested',
            'favorited',
            'favoritesCount',
        )
        read_only_fields = ('tags',)

    # class JSONAPIMeta:
    #     included_resources = ['comments', 'tags']

    def create(self, validated_data):
        author = self.context.get('author', None)
        tags = validated_data.pop('tags', [])
        post = Post.objects.create(author=author, **validated_data)

        for tag in tags:
            post.tags.add(tag)

        return post