# Generated by Django 3.0.8 on 2020-07-18 13:33

import requests
from django.db import migrations


def import_posts(apps, schema_editor):
    Post = apps.get_model('posts', 'Post')
    User = apps.get_model('users', 'User')

    url = "https://jsonplaceholder.typicode.com/posts"
    response = requests.get(url)
    api_posts = response.json()

    created_posts = []

    for post in api_posts:
        user = User.objects.get(pk=post.get("userId"))
        created_posts.append(Post(
            author=user,
            body=post.get("body"),
            title=post.get("title")
        ))

    Post.objects.bulk_create(created_posts)


class Migration(migrations.Migration):

    dependencies = [
        ('posts', '0001_initial'),
        ('users', '0002_auto_20200718_1547')
    ]

    operations = [
        migrations.RunPython(import_posts),
    ]
