3

at first it looked simple, now I got confused. I wrote data structure and now struggling to get it. So far what I have:

class Area(models.Model):
    name = models.CharField(max_length=128)
    ...

class Category(models.Model):
    name = models.CharField(max_length=128)
    ....

class Venue(models.Model):
    name = models.CharField(max_length=128)
    category = models.ForeignKey(Category, related_name='venues')
    area = models.ForeignKey(Area, related_name='venues')

And I need based on Area pk get categories with venues in it. Is it possible to do so using django rest framework? The result should look something like:

  {
    "pk": 1,
    "name": "London",
    "categories": [
        {
             "pk": 1,
             "name": "Bars",
             "venues": [
                 {
                      "pk": 1,
                      "name": "Cool bar"
                 },
                 {
                      "pk": 2,
                      "name": "Cooler bar"
                 },
                 {
                      "pk": 3,
                      "name": "Coldest bar"
                 },
            ]
        }
    ]

}

Ideally I need something like this:

class VenueSerializer(serializers.ModelSerializer):
  .....

class CategorySerializer(serializers.ModelSerializer):
    venues = VenueSerializer(read_only=True, many=True)

    class Meta:
        model = Category
        fields = ('pk', 'name', 'venues', )

class AreaSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(read_only=True, many=True)

    class Meta:
        model = Area
        fields = ('pk', 'name', 'categories', )

But of course this will not work since Area is not directly related to Category. So my question, is it possible to do this without changing data structure?

1 Answer 1

2

It's a little ugly, but if you're set on the object model, you can do this using DRF's SerializerMethodField.

Your Area serializer would then look something like:

class AreaSerializer(serializers.ModelSerializer):
    categories = SerializerMethodField()

    def get_categories(self, obj):
        # this will find all categories with a venue in given area
        categories = Category.objects.filter(venues__area=obj)
        serializer = CategorySerializer(categories, many=True)
        return serializer.data

    class Meta:
        model = Area
        fields = ('pk', 'name', 'categories', )

Without optimization, this structure will generate A LOT of database queries. I'd recommend using Django's prefetch_related operation to reduce the number of redudant queries.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.