Fetch and return category and all related objects

Viewed 21

I have a Bookmark and a BookmarkCategory object. I'd like to be able to fetch JSON that looks like this:

GET -> localhost:8000/api/bookmarks

[
  "python": {
    "title": "Python",
    "bookmarks": [
      {
        "title": "Python Documentation",
        "url": "https://docs.python.org"
      }
    ]
  },
  "javascript": {
    "title": "Javascript",
    "bookmarks": [
      {
        "title": "Python Documentation",
        "url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript"
      }
    ]
  }
]

Here's my models:

class BookmarkCategory(models.Model):
  title = models.CharField(max_length=255)


class Bookmark(models.Model):
  title = models.CharField(max_length=255)
  url = models.CharField(max_length=255)
  category = models.ManyToManyField(BookmarkCategory)

Here's how I would query all the BookmarkCategory objects:

from .models import BookmarkCategory

bookmarks = BookmarkCategory.objects.all()

The JSON doesn't have to look exactly like this. I just need to get all my BookmarkCategory objects along with all the related Bookmark objects so I can iterate over them after I make a GET request to fetch them.

1 Answers

You'll have to use select_related on "bookmark_set", to fetch them along. If you are using DRF, you need to create a nested serializer configuration for bookmarks. Here is an example without DRF:

categories = BookmarkCategory.objects.select_related("bookmark_set")
items = []
for category in categories:
    items.append(
        {
            "title": category.title,
            "bookmarks": category.bookmark_set.values_list("title", "url"),
        }
    )
Related