创建模型时使用外键自动创建模型-Django [英] Auto-create model with foreign key when model is created - Django

查看:85
本文介绍了创建模型时使用外键自动创建模型-Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在我的网页上添加评论部分,并希望用户能够赞成或反对评论。

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

我的模型如下:

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)

当a用户发布评论,我希望它还创建链接到该评论的投票模型。

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

我是django和编程的新手,但据我了解,我需要创建一个save钩子或类似的东西吗?

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

推荐答案

您可以覆盖<$ c $的 save()方法$ c>评论模型,即:

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.

这篇关于创建模型时使用外键自动创建模型-Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆