0

I have following model:

class Comment(models.Model):
    uuid = models.CharField(max_length=40, default='random')
    news = models.ForeignKey('News')
    user = models.OneToOneField(User, primary_key=True) # ForeignKey('User')
    text = models.CharField(max_length=300, null=True)
    upvotes = models.PositiveIntegerField(default=0)
    downvotes = models.PositiveIntegerField(default=0)
    votes = models.ManyToManyField(User, through='Vote', related_name='votes_table')


class Vote(models.Model):
    cmt = models.ForeignKey(Comment)
    user = models.ForeignKey(User)
    vote_type = models.SmallIntegerField(default=0) # vote_type is +1 for upvote & -1 for downvote

When a user submits a new comment, I initialize a new one, like this: c = Comment(uuid=uuid.uuid4(),news=n, user=request.user, text=comment_text). Now the problem is, when I print c.votes.exists(), it's True. How did this comment c have an entry in the comments_votes table?

Kamal Banga
  • 107
  • 1
  • 10
  • Did you save the new comment before checking if votes exists? You can see the generated SQL for the exists() call in a django shell when django is in DEBUG model using from django.db import connection print connection.queries[-1] – Lyudmil Nenov May 14 '15 at 12:56

1 Answers1

0

The generated 'sql': u'SELECT (1) AS "a" FROM "auth_user" INNER JOIN "app_vote" ON ("auth_user"."id" = "app_vote"."user_id") WHERE "app_vote"."cmt_id" = 62 LIMIT 1'

As the primary key for Comment is User, c.votes.exists() actually checks if the user has any votes rather than checking if the comment has any votes.

P.S. You can get the comment votes with a query on Vote if you filter by the comment uuid instead of pk

Lyudmil Nenov
  • 247
  • 2
  • 6