Reputation: 46
I want to create the relationship between a person and the news article it got mentioned in.
person/models.py
class Person(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=40)
news_mentioned = models.ManyToManyField(News, blank=True)
news/models.py
class News(models.Model):
title = models.CharField(max_length=250)
abstract = models.TextField(max_length=1000, null=True, blank=True)
description = models.TextField(max_length=5000, null=True, blank=True)
url = models.URLField(unique=True)
ne_person = models.CharField(max_length=250, blank=True, null=True)
Extract from the celery task:
article = News.objects.get(pk=pk)
person = Person.objects.update_or_create(first_name=fname, last_name=lname)
person.save()
mentioned = Person.objects.get(person.id).news_mentioned(article.id)
What am I making wrong here
Upvotes: 0
Views: 1706
Reputation: 1829
The models are correct.
To add an Article to the Person you need to use .add()
s. https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/#many-to-many-relationships
Try it like this:
article = News.objects.get(pk=pk)
person, created = Person.objects.update_or_create(first_name=fname, last_name=lname)
person.save()
person.news_mentioned.add(article)
mentioned = person.news_mentioned.all()
Upvotes: 1
Reputation: 46
I did isolate the problem and it turned out that the issue is related to update_or_create
, because it returns a Tuple.
It now works like this:
person, created = Person.objects.update_or_create(first_name=fname, last_name=lname)
person.save()
article = News.objects.get(pk=pk)
person.news_mentioned.add(article)
Upvotes: 1