Aleksandr Lozko
Aleksandr Lozko

Reputation: 43

Saving data to models in Django with ForeignKey relationship

When I am parsing a page I can't save category and topic to DB in Django. What should I do?

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)
    ...

I wrote it, but it doesn't work. Most likely add() cannot be used with models.ForeignKey, right? If yes, how to do?

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)

Upvotes: 1

Views: 70

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

Since it is a (non-null) ForeignKey, the field topic and category should refer to exactly one Topic and Category object.

Therefore you should first construct the Category and Topic object, and then create a Page that uses these objects, like:

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
)

I would furthermore advice to use category_name and topic_name over category and topic when you construct your Category and Topic objects, since otherwise, you introduce confusion.

Upvotes: 2

Related Questions