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?
Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With