将数据保存到具有ForeignKey关系的Django模型中

问题描述 投票:1回答:1

解析页面时,我无法将类别和主题保存到Django中的DB。我该怎么办?

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()无法与model.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)
python django web
1个回答
0
投票

因为它是(非空)ForeignKey,所以字段topiccategory应该引用精确地一个TopicCategory对象。

因此,您应该first构造CategoryTopic对象,然后创建使用这些对象的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_nametopic_name对象时,在categorytopic上使用CategoryTopic,否则会引起混淆。

© www.soinside.com 2019 - 2024. All rights reserved.