我一直在为此苦苦挣扎了一段时间,似乎无法在任何其他线程上找到答案。
我正在尝试以编程方式向 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)
我正在尝试运行一些代码来添加我从详细信息视图(基于类的视图)中的另一个位置提取的一些数据
我为此编写的代码在这里:
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评论,并将它们存储在数据库中。我遇到的问题如下:
ValueError: Cannot assign "'Post object (22)'": "Comment.post" must be a "Post" instance.
我做错了什么?
根据这个元指令,我已将@Sajad的以下评论转换为社区维基,表明这个问题已解决。
在最后一行中,您将
post_to
格式化为字符串并将其分配给post
,该实例必须是Post
实例而不是 str。只需写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)}')