首页 > 解决方案 > 使用 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)

标签: pythondjango

解决方案


由于它是 (non-null) ForeignKey,因此该字段topiccategory应该完全引用一个TopicCategory对象。

因此,您应该首先构造CategoryandTopic对象,然后创建一个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_nameand topic_nameover category,否则你会引入混乱。topicCategoryTopic


推荐阅读