Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TypeError: Model instances without primary key value are unhashable

Tags:

python

django

I have my models.py as follows:

class Article(models.Model):
    date = models.DateTimeField(null=True, blank=True)
    title = models.TextField(default=None, null=True, blank=True)
    content = models.TextField(default=None, null=True, blank=True)
    author = models.TextField(default=None, null=True, blank=True)
    url = models.CharField(max_length=255, default=None, null=True, blank=True, unique=True)


class Keyword(models.Model):
    word = models.CharField(max_length=80)

    def __str__(self):
        return self.word
    article = models.ForeignKey(Article, related_name='keywords_found', null=True, blank=True)

I encounter an error when I try to save the data like this:

Article.objects.create(date=publish_date, title=article.title, content=article.text, author=article.authors, url=url, keywords_found=keywords_found)

Here, keywords_found is a list of Keyword objects.

The error is:

TypeError: Model instances without primary key value are unhashable

Where am I going wrong?

Django version : 1.10

like image 544
androidnoob Avatar asked Oct 15 '25 18:10

androidnoob


1 Answers

Try saving it this way -

    art = Article.objects.create(date=publish_date,
                                title=article.title, 
                                content=article.text, 
                                author=article.authors,
                                url=url)

    Keyword.objects.create(word=keywords, article=art)
like image 132
utkbansal Avatar answered Oct 18 '25 08:10

utkbansal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!