【问题标题】:Add entries to model with ForeignKey使用 ForeignKey 向模型添加条目
【发布时间】:2021-03-16 00:13:01
【问题描述】:

我已经为此苦苦挣扎了一段时间,似乎无法在任何其他线程上找到答案。

我正在尝试以编程方式向 Django 中的模型添加一些条目,我尝试添加的模型有一个外键,这就是我要挂断的内容。

我的两个模型是:

class Post(models.Model):
    direct_url = models.URLField(unique=True)
    post_url = models.URLField()
    post_title = models.CharField(max_length=300)
    time_posted = models.DateTimeField(default=timezone.now)

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    content = models.CharField(max_length=500)
    author = models.CharField(max_length=60)
    date_created = models.DateTimeField(default=timezone.now)

我正在尝试运行一些代码来添加一些我从 DetailView(基于类的视图)中的另一个位置提取的数据

我的代码在这里:

class PostDetailView(DetailView):
model = Post
for i in hot:
    if i.url.endswith(Endings):
        post_to = model.objects.get(direct_url=i.url)
        submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
        submission.comments.replace_more(limit=None)
        for comment in submission.comments.list():
            Comment.objects.create(post=f'{post_to}', content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')

我正在尝试提取 reddit cmets,并将它们存储在数据库中。我遇到的问题如下:

ValueError: Cannot assign "'Post object (22)'": "Comment.post" must be a "Post" instance.

我做错了什么?

【问题讨论】:

  • 在最后一行,您将post_to 格式化为字符串并将其分配给post,它必须是Post 实例而不是str。写post=post_to
  • 我认为它需要一个字符串。这很尴尬!哈哈。不过感谢您的帮助!
  • 这件事发生在我们所有人身上,不要出汗!
  • 现在我收到一条错误消息,“django.db.utils.OperationalError: no such table: homepage_post”——主页是我的应用程序的名称。
  • 如果我在views.py中注释掉最近的代码,一切正常。使用那里的代码,我无法运行 manage.py makemigrations 或迁移。我也尝试过运行syncdb,但这也不起作用。它似乎与视图中添加的代码直接相关,就好像我删除了它工作的代码一样。我尝试删除数据库并创建一个新数据库,但其中的 views.py 代码仍然出现相同的错误。

标签: python django django-models foreign-keys


【解决方案1】:

根据this meta directive,我已将@Sajad 的以下评论转为社区wiki,表示此问题已解决。

在最后一行,您将post_to 格式化为字符串并将其分配给post,它必须是Post 实例而不是字符串。写post=post_to就行了。

以下代码应该可以工作:

class PostDetailView(DetailView):
model = Post
for i in hot:
    if i.url.endswith(Endings):
        post_to = model.objects.get(direct_url=i.url)
        submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
        submission.comments.replace_more(limit=None)
        for comment in submission.comments.list():
            Comment.objects.create(post=post_to, content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多