我想根據 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,Tags 表應如下所示:
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。保存帖子標題后,我該如何保存標簽?
uj5u.com熱心網友回復:
保存標簽時,您應該參考帶有物件的帖子,而不是它的 pk。Django ORM 會為你做到這一點。并且在使用 create 時,您不需要再次保存它,因為create()已經保存了它。在回圈中嘗試以下操作:
Tags.objects.create(name=article_tags[i], post=post)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399521.html
標籤:姜戈 PostgreSQL的 标签 RSS 提要解析器
上一篇:為什么我有TypeError:expectedstringorbytes-likeobject-django
下一篇:如何更改條件運算式的默認列名
