【发布时间】:2021-12-30 20:18:12
【问题描述】:
我想从 RSS 提要帖子的标题创建文章标签。然后将标签保存到带有标题的 post_id 的数据库中,我同时从中获得了标签。像这样的:
Title = "Voyant raises $15M to scale production of its tiny, inexpensive lidar tech"
Tags = ['Voyant', 'Raises', '$15M', 'To', 'Scale', 'Production', 'Of', 'Its', 'Tiny', 'Inexpensive', 'Lidar', 'Tech']
假设 post_id 为 1,标签表应如下所示:
id | tag | post_id
--------------------------------
1 | Voyant | 1
2 | Raises | 1
我的表中有 3 个模型(来源、帖子和标签)。
class Source(models.Model):
name = models.CharField(max_length=500, verbose_name='Website Name')
class Posts(models.Model):
post_title = models.CharField(max_length=500, verbose_name='Post Title')
source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source')
class Tags(models.Model):
name = models.CharField(max_length=500)
post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts')
到目前为止,我能够拆分上面的标题。
title = item.title
strip_away = title.replace(",", "").replace(":", "").replace("(", "").replace(")", "").replace("'", "").replace("[", "").replace("]", "").replace("!", "").replace("?", "").replace("-", " ")
capital = strip_away.title()
article_tags = capital.split()
但现在我的问题出现在保存部分。
def fetch_articles():
feed = feedparser.parse("my_site_of_preference")
source = Source.objects.get(pk=1)
source_id = int(source.pk)
source_name = source
save_new_articles(source_id, source_name, feed)
def save_new_articles(source_id, source_name, feed):
selected_source_id = source_id
for item in feed.entries:
title = item.title
""" The splitting code """
if not Posts.objects.filter(post_title=title).exists():
post = Posts(post_title = title, source_id = selected_source_id)
post.save()
for i in range(len(article_tags)):
tags = Tags.objects.create(name = article_tags[i], post_id = source_name.pk)
tags.save()
我不断收到错误:
django.db.utils.IntegrityError: insert or update on table "Posts_tags" violates foreign key constraint "Posts_tags_post_id_3e6ae939_fk_Posts_posts_id"
DETAIL: Key (post_id)=(1) is not present in table "Posts_posts".
帖子还没有被保存创建一个post_id,它可以在保存标签时用作PK。保存帖子标题后如何保存标签?
【问题讨论】:
-
我认为它不应该在
Posts(post_title = title, source_id = selected_source_id,)这里发布post_title并最后删除多余的逗号。 -
@Ahtisham 为逗号道歉。这是一个错字。您能否详细说明您的解决方案?
标签: django postgresql tags rss feedparser