snamstorm
snamstorm

Reputation: 133

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?

Upvotes: 7

Views: 6716

Answers (2)

realmaniek
realmaniek

Reputation: 513

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.

Upvotes: 3

Selcuk
Selcuk

Reputation: 59445

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.

Upvotes: 10

Related Questions