Answer the question
In order to leave comments, you need to log in
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
)
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
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)
def get_is_subscribed(self, obj):
return self.context['user'] in obj.followers.all()
# или obj.follower.filter(id=self.context['user'].id).exists()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question