Creating a model with a foreign key automatically when creating a model - Django

I am creating a comment section on my web page and want users to be able to raise or lower the comment.

My models are as follows:

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 submits a comment, I want him to also create a voting model associated with this comment.

I'm new to django and programming, but in my opinion do I need to create a backup hook or something like that?

+4
source share
2 answers

You can override the save()model method Comment, i.e.:

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

I suggest you read the documentation for a better understanding.

+4
source

:

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)

, , . .

+1

All Articles