I have a post model and it has likes (responses). I would like to see if the logged in user has already liked a post and so I need to check if the id of the logged in user matches any of the users that liked a post.
Here is the post model:
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1, related_name="posts")
body = models.TextField("content", blank=True, null=True, max_length=5000)
slug = AutoSlugField(populate_from=["category", "created_at"])
video = models.FileField(upload_to=video_directory_path, null=True, blank=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="posts"
)
published = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "post"
verbose_name_plural = "posts"
db_table = "posts"
ordering = ["created_at"]
get_latest_by = "created_at"
def __str__(self):
return self.body[0:30]
def get_absolute_url(self):
return self.slug
def one_image(self):
return PostImage.objects.all().filter(post=self)[:1]
Here is the Post Response (like) model:
class PostResponse(models.Model):
like = "like"
feelings = [
(like , "like"),
]
response = models.CharField(max_length=15,choices=feelings, default=like)
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="responses")
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
unique_together = ['post', 'user']
verbose_name = "Post response"
verbose_name_plural = "Post responses"
db_table = "post_responses"
def __str__(self):
return str(self.response)
Here is the Post Response serializer and it works kind of because there is only one post response. How can I check if the user id matches any of the responses, so like a list of responses?
class PostResponseSerializer(serializers.ModelSerializer):
liked = serializers.SerializerMethodField()
class Meta:
model = PostResponse
fields = [
"post",
"response",
"user",
"liked",
]
def get_liked(self, obj):
request = self.context.get('request', None)
if request:
loggedUser = self.context["request"].user.id
if loggedUser == obj.user.id:
return True
CodePudding user response:
You already have the relationship https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_one/
In order to access user liked responses just access it via user instance
user = request.user
liked_responses = user.postresponse_set.all()
Assume you already have a PostResponseViewSet
. You can put this in your view set via get_queryset
method:
class PostResponseViewSet(ModelViewSet):
# ...other attributes
def get_queryset(self):
return self.request.user.postresponse_set.all()
CodePudding user response:
You can access like via post instance by Reverse Relationship using related_name
class PostResponseSerializer(serializers.ModelSerializer):
liked = serializers.SerializerMethodField()
class Meta:
model = PostResponse
fields = [
"post",
"response",
"user",
"liked",
]
def get_liked(self, obj):
request = self.context.get('request', None)
if request:
loggedUser = self.context["request"].user
is_liked = obj.responses.filter(user=loggedUser).exists()
return is_liked