如何在Django中通过拆分标题创建文章标签 [英] How to create Article tags from splitting the Title in Django
本文介绍了如何在Django中通过拆分标题创建文章标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从RSS提要帖子的标题创建文章标记。然后,将标签保存到DB中,并使用我同时从其获得标签的标题的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个模型(源、帖子和amp;标记)。
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。如何在保存帖子标题后保存标签?
推荐答案
保存标签时,应该引用带有Object的帖子,而不是引用其主键。Django ORM会为您做到这一点。使用CREATE时,create()已经保存,不需要再次保存。在您的循环中尝试以下操作:
Tags.objects.create(name=article_tags[i], post=post)
这篇关于如何在Django中通过拆分标题创建文章标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文