如何在Django中通过拆分标题来创建文章标签



我想从RSS提要文章的标题创建文章标签。然后将标签保存到一个DB中,该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,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。保存帖子标题后,我该如何保存标签?

保存标签时,应该引用带有对象的post,而不是它的pk。Django ORM会帮你做到这一点。当使用create时,您不需要再次保存它,因为create((已经保存了它

Tags.objects.create(name=article_tags[i], post=post)

相关内容

  • 没有找到相关文章

最新更新