D
D
dert23132022-02-13 12:52:21
Django
dert2313, 2022-02-13 12:52:21

How to implement check in get_is_subscribed method via related_name?

Subscription Model

class Follow(models.Model):
    user = models.ForeignKey(
        User,
        related_name='follower',
        on_delete=models.CASCADE
    )
    author = models.ForeignKey(
        User,
        related_name='following',
        on_delete=models.CASCADE
    )

serializer with method
class UserFollowSerializer(serializers.ModelSerializer):
    is_subscribed = serializers.SerializerMethodField()
    recipes = UserRecipeSerializer(many=True, read_only=True)
    recipes_count = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'email',
            'id',
            'username',
            'first_name',
            'last_name',
            'is_subscribed',
            'recipes',
            'recipes_count'
        )

    def get_is_subscribed(self, obj):
        return obj.following.filter(user=self.context['user']).exists()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
korid24, 2022-02-15
@korid24

Perhaps it would make life easier for you (not only in this particular case) by adding an m2m connection of the user model to itself by type

class User:
    ...
    subscriptions = models.ManyToManyField('self', related_name='followers', symmetrical=False)

then it would be
def get_is_subscribed(self, obj):
    return self.context['user'] in obj.followers.all()
   # или obj.follower.filter(id=self.context['user'].id).exists()

if the Follow model is still needed as an intermediate table, you can add the through attribute to ManyToManyField

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question