Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-create model with foreign key when model is created - Django

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?

like image 202
snamstorm Avatar asked Mar 17 '15 20:03

snamstorm


People also ask

Does Django automatically index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .

What is __ str __ In Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

Can a model have two foreign keys in Django?

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.

How does ForeignKey work in Django?

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.


1 Answers

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.

like image 105
Selcuk Avatar answered Sep 28 '22 19:09

Selcuk