7

I am making a comments section on my webpage and want users to be able to upvote or downvote a comment.

My models are as such:

class Comment(models.Model):
    owner = models.ForeignKey(User)
    body = models.TextField(null=True, blank=True, max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


class Vote(models.Model):
    comment = models.ForeignKey(Comment)
    upvote = models.SmallIntegerField(null=True, blank=True, default=0)
    downvote = models.SmallIntegerField(null=True, blank=True, default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

When a user posts a comment, I want it to also create a Vote model that is linked to that comment.

I am new to django and programming but from my understanding, I need to create a save hook or something similar?

snamstorm
  • 133
  • 1
  • 7
  • Out of curiosity, do you need to implement this as a many-to-one (especially if there's multiple things you can vote on this will not be reusable)? I've always seen voting implemented simply as a single field like this http://django-vote.readthedocs.org/en/latest/getting_started.html – Charlie Mar 18 '15 at 14:08

2 Answers2

10

You can override the save() method of Comment model, ie:

class Comment(models.Model):
    ...
    def save(self, **kwargs):
        super(Comment, self).save(**kwargs)
        vote = Vote(comment=self)
        vote.save()

I suggest you to read the documentation for a better insight.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
3

Consider this code:

class ModelA(models.Model):
    name = models.CharField(max_length=30)

    @classmethod
    def get_new(cls):
        return cls.objects.create().id



class ModelB(models.Model):
    thing = models.OneToOneField(ModelA, primary_key=True, default=ModelA.get_new)
    num_widgets = IntegerField(default=0)

Of course you can use lambda as well, as long as you return integer id of related object. I don't recommend overwritting save method.

realmaniek
  • 465
  • 5
  • 11
  • "I don't recommend overwritting save method." -- Can you explain why? Accepted answer recommends exactly that, maybe there is a good reason why not to do it that way? – John Robinson Jul 04 '19 at 19:35
  • 1
    One thing to be careful of: this calls a `create` on the related model without a `save` on the current model. Here, if we call `ModelB()`, we will cause a `ModelA` object to be created and saved, which may cause an unintended proliferation of saved `ModelA` objects. – Wesley Smith Oct 25 '19 at 17:32