django rest update_or_create

Viewed 800

Background:

I am trying to create a system which allows users to vote on comments written by other users (similar to Reddit). Users have the choice of three vote values: -1, 0, or 1. I have created a POST API (using django rest-framework) that will store a user's vote with respect to a particular comment. If the user has already voted on the given comment, then it will update the existing user’s vote value to the new one.

I drew inspiration from this post:Django RF update_or_create

Problem:

Once a comment has had one user submit a vote on it, Django creates a duplicate comment object with the same ID/primary key whenever another user votes on the same comment. I have taken a screenshot of my admin page where it says I have 3 objects to select but only a single comment. Why is it doing this and how can I prevent it?

Screenshot of my comment admin page

I am new to Django. I suspect I might be doing something wrong when I define my own "create" method in my serializer. I'd appreciate any help. Thanks!

models.py:

Comment model:

class Comment(models.Model):
    location_property_category = models.ForeignKey('locations.LocationPropertyCategory',on_delete=models.CASCADE,related_name='comments',null=True)
    author = models.ForeignKey('auth.User',on_delete=models.PROTECT,related_name='comments')
    location = models.ForeignKey('locations.Location',on_delete=models.CASCADE,related_name='comments')
    text = models.TextField()
    create_date = models.DateTimeField(default=timezone.now())
    published_date = models.DateTimeField(blank=True,null=True)
    approved_comment = models.BooleanField(default=False)

    objects = CommentManager()

    def approve(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

    def save(self, *args, **kwargs):
        if self.approved_comment is True:
            self.published_date = timezone.now()
        super(Comment, self).save(*args, **kwargs)

    def sum_vote(self):
        return self.upvotedownvotes.aggregate(Sum('vote')).get('vote__sum') or 0

Vote model:

class UpVoteDownVote(models.Model):
    UPVOTE = 1
    NEUTRALVOTE = 0
    DOWNVOTE = -1

    VOTES = (
        (UPVOTE, 'Upvote'),
        (NEUTRALVOTE, 'Neutralvote'),
        (DOWNVOTE, 'Downvote')
    )

    vote = models.SmallIntegerField(choices=VOTES)
    user = models.ForeignKey('auth.User', related_name='upvotedownvotes', on_delete=models.CASCADE)
    comment = models.ForeignKey(Comment, related_name='upvotedownvotes', on_delete=models.CASCADE)
    date_voted = models.DateTimeField(default=timezone.now())

    class Meta:
        unique_together     = (('user','comment'),)

Comment manager model:

class CommentManager(models.Manager):
    def get_queryset(self):
    return super(CommentManager, self).get_queryset().order_by('-upvotedownvotes__vote')

serializers.py Vote serializer:

class UpVoteDownVoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = UpVoteDownVote
        fields = ('vote','comment')

    def get_fields(self):
        fields = super(UpVoteDownVoteSerializer, self).get_fields()
        fields['comment'].queryset = Comment.objects.filter(approved_comment=True)
        return fields

    def create(self, validated_data):

        votedata, created = UpVoteDownVote.objects.update_or_create(
        user=validated_data.get('user', None),
        comment=validated_data.get('comment', None),
        defaults={'vote': validated_data.get('vote', None),
        })
        return votedata

views.py

class UpVoteDownVoteCreateApiView(generics.CreateAPIView):
    serializer_class = UpVoteDownVoteSerializer
    permission_classes = [IsAuthenticated]



    def perform_create(self,serializer):
        serializer.save(user=self.request.user)

Comment app admin.py

class CommentAdmin(admin.ModelAdmin):
    readonly_fields = ('id',)

admin.site.register(Comment,CommentAdmin)
1 Answers

Welcome to StackOverflow!

Your problem is in CommentManager:

queryset.order_by('-upvotedownvotes__vote')

This query basically creates LEFT_OUTER_JOIN. So you result looks like:

comment#1 upvote#1
comment#1 upvote#2
comment#1 upvote#3

That is why you are seeing comment#1 3 times.

I believe that you want to use something like this: https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#order-by

Related