Shyrtle
Shyrtle

Reputation: 647

Add entries to model with ForeignKey

I been struggling with this for a while and can't seem to find an answer on any of the other threads.

I am trying to programmatically add some entries to a model in Django, the model I am trying to add to has a foreign key, and this is what I am getting hung up on.

My two models are:

class Post(models.Model):
    direct_url = models.URLField(unique=True)
    post_url = models.URLField()
    post_title = models.CharField(max_length=300)
    time_posted = models.DateTimeField(default=timezone.now)

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    content = models.CharField(max_length=500)
    author = models.CharField(max_length=60)
    date_created = models.DateTimeField(default=timezone.now)

I am trying to run some code to add some data I am pulling from another location in the DetailView (Class based view)

The code that I have for that is here:

class PostDetailView(DetailView):
model = Post
for i in hot:
    if i.url.endswith(Endings):
        post_to = model.objects.get(direct_url=i.url)
        submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
        submission.comments.replace_more(limit=None)
        for comment in submission.comments.list():
            Comment.objects.create(post=f'{post_to}', content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')

I am trying to pull the reddit comments, and store them in a database. The problem I am running into is the following:

ValueError: Cannot assign "'Post object (22)'": "Comment.post" must be a "Post" instance.

What am I doing wrong?

Upvotes: 1

Views: 71

Answers (1)

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3550

As per this meta directive, I have turned the following comment by @Sajad into a community wiki, signalling that this question is solved.

In the last line, you're formatting post_to to string and assigning it to post which must be a Post instance and not str. Just write post=post_to.

The following code should work:

class PostDetailView(DetailView):
model = Post
for i in hot:
    if i.url.endswith(Endings):
        post_to = model.objects.get(direct_url=i.url)
        submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}')
        submission.comments.replace_more(limit=None)
        for comment in submission.comments.list():
            Comment.objects.create(post=post_to, content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}')

Upvotes: 1

Related Questions