【问题标题】:How to create Article tags from splitting the Title in Django如何通过在 Django 中拆分标题来创建文章标签
【发布时间】: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


【解决方案1】:

保存标签时,您应该使用对象引用帖子,而不是它的pk。 Django ORM 将为您做到这一点。而且使用create的时候不需要再保存,create()已经保存了。在您的循环中尝试以下操作:

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

【讨论】:

  • 谢谢!!!这解决了我的问题。请问您是否知道我如何将相同的标签分组并获得一个计数为this 的列,以便在过滤期间我可以获得具有给定标签的所有帖子?
  • 查询标签时查看annotating a count。 SO中有很多答案。否则发布一个新问题。
  • 酷。我找到了答案here。非常感谢!
猜你喜欢
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 2018-07-20
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多