python - 使用 ForeignKey 关系将数据保存到 Django 中的模型
问题描述
当我解析页面时,我无法将类别和主题保存到 Django 中的数据库。我应该怎么办?
class Category(models.Model):
category = models.CharField(max_length=50)
slug = models.CharField(max_length=60, unique=True)
class Topic(models.Model):
topic = models.CharField(max_length=50)
slug = models.CharField(max_length=60, unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
...
我写了它,但它不起作用。很可能 add() 不能与 models.ForeignKey 一起使用,对吧?如果是,怎么办?
from django.template.defaultfilters import slugify
...
page = {
'datetime': datetime,
'title':title,
'slug':slug,
'short_text':short_text,
'text':text,
'image':image_name,
'img_source':img_source,
'page_source':page_source,
}
try:
page = Page.objects.create(**page)
except Exception as e:
print(e, type(e))
category = {'category':category, 'slug':slugify(category)}
category, created = Topic.objects.get_or_create(**category)
page.category.add(category)
topic = {'topic':topic, 'slug':slugify(topic)}
topic, created = Topic.objects.get_or_create(**topic)
page.topic.add(topic)
解决方案
由于它是 (non-null) ForeignKey
,因此该字段topic
和category
应该完全引用一个Topic
和Category
对象。
因此,您应该首先构造Category
andTopic
对象,然后创建一个Page
使用这些对象的对象,例如:
category, created = Category.objects.get_or_create(
category=category_name,
slug=slugify(category_name)
)
topic, created =Topic.objects.get_or_create(
topic=topic_name,
slug=slugify(topic_name),
category=category
)
page = Page.objects.create(
datetime=datetime,
title=title,
slug=slug,
short_text=short_text,
text=text,
image=image_name,
img_source=img_source,
page_source=page_source,
category=category,
topic=topic
)
我还建议在你构造你的和对象时使用category_name
and topic_name
over category
,否则你会引入混乱。topic
Category
Topic
推荐阅读
- javascript - 如何将js小部件转换为amp组件
- python - 如何找到所有可能的参数和函数组合
- python - collatz func 在用 python 自动化无聊的东西
- react-redux - 有条件地连接组件时“对象作为 React 子项无效”Redux 错误?
- javascript - iife 与 document.title 的简单语句行为
- c++ - 将函数标识符作为右值引用传递并对其应用 std::move()
- docker - 不健康的 docker 容器未由 docker 本机运行状况检查重新启动
- sql - 如何从下面的多个时间和时间计算总小时数?
- json - 如何修复 XML HTTP 请求中的“下标超出范围”错误
- android - 如何将一个android活动连接到另一个?