UNC BACS 350

Web Apps with Python/Django

Logo

Lesson 37 - JSON & Test Fixtures

LEARN

Office Hours

Today

Catalog of Design Patterns

JSON data

```python import json

x = { "model": "book.chapter", "pk": 2, "fields": { "book": 1, "order": 2, "title": "Technical Debt", "markdown": "", "html": "", "document": "02.md" } }

sort the result alphabetically by keys:

print(json.dumps(x, indent=4, sort_keys=True)) ```

Working with Data

dumpdata

```bash $ python manage.py dumpdata

$ python manage.py dumpdata --indent 4 book.chapters ```

loaddata

```bash $ python manage.py loaddata

$ python manage.py loaddata Documents/Test/data.chapters.json ```

Tests with Data

Test Fixtures

```python class BookFixtureTest(TestCase): fixtures = ['Documents/Test/data.json']

def test_with_data(self):
    self.assertEqual(len(Author.objects.all()), 1)
    self.assertEqual(len(Book.objects.all()), 2)
    self.assertEqual(len(Chapter.objects.all()), 70)

```

Django Documents

BUILD

Practice