-
-
Save relational/060decacb9378e604cd6 to your computer and use it in GitHub Desktop.
Model for Reddit-like posts and votes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LinkPost(models.Model): | |
link = models.URLField(max_length=1000, null=False, verbose_name="Link", unique=True) | |
title = models.CharField(max_length=1000, null=False, verbose_name="Title") | |
creator = models.ForeignKey(User,related_name="posts", verbose_name="Sendandi") | |
upvotes = models.IntegerField(null=False, verbose_name = "Upvotes", default=0) | |
downvotes = models.IntegerField(null=False, verbose_name = "Downvotes", default=0) | |
description = models.TextField(blank=True, verbose_name="Description") | |
def recompute_votes(self): | |
self.upvotes = UserPostVote.objects.filter(post=self, value=1).count() | |
self.downvotes = UserPostVote.objects.filter(post=self, value=-1).count() | |
self.save() | |
def __unicode__(self): | |
return unicode(self.create_time)+unicode(self.link) | |
class UserPostVote(models.Model): | |
user = models.ForeignKey(User,related_name="post_votes") | |
post = models.ForeignKey(LinkPost,related_name="user_votes") | |
value = models.IntegerField(null=False, default=0) | |
class Meta: | |
unique_together = ("user","post") | |
def vote(self,voteval): | |
""" Change the vote value to voteval and re-adjust the de-normalized vote count of the post """ | |
#Reset values, before setting new vote values, updating score and saving | |
#Reset vote value to 0, and update comment creator and comment votes | |
#WITHOUT SAVING | |
if(self.value != 0): #If vote is zero, nothing to reset | |
if(self.value>0): | |
self.post.upvotes -= 1 | |
if(self.value<0): | |
self.post.downvotes -= 1 | |
self.value = 0 | |
#values resetted | |
#now perform vote | |
if(voteval>0): | |
self.post.upvotes += 1 | |
self.value = 1 | |
if(voteval<0): | |
self.post.downvotes += 1 | |
self.value = -1 | |
self.post.save() | |
self.save() | |
def __unicode__(self): | |
return u"%s %s %s" % (self.post.id,self.post, self.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment