Question

I am attempting to fetch nested objects but not quite sure how to achieve this. My model is as shown:

class Brand(models.Model)
    name = models.CharField(max_length=128)

class Size(models.Model)
    name = models.CharField(max_length=128)

class Brand_Size(models.Model)
    brand = models.ForeignKey(Brand)
    size = models.ForeignKey(Size)

class Brand_Size_Location(models.Model)
    location = models.ForeignKey(Location)
    brand_size = models.ForeignKey(Brand_Size)

I filter objects in Brand_Size_Location by location which can occur 1..x. I want my serializer to output the results in terms of the model Brand (BrandSerializer). Since my resultset can be 1..x and furthermore the occurrence of Brand can be duplicates i would like to eliminate these aswell at the same time.

Was it helpful?

Solution

You should be able to do this fairly easily by including a serializer field in your BrandSerializer:

class BrandSerializer(serializers.ModelSerializer):
    brand_sizes = BrandSizeSerializer(
        source='brand_size_set',
        read_only=True
    )

    class Meta:
        model = Brand
        fields = (
            'id',
            ...add more fields you want here
            'brand_sizes')

You can simlarly create the brand size serializer to nest the locations

Filtering on this relationship occurs in the view and will need a custom filter. Here's a basic example using a ListView:

class BrandFilter(django_filters.FilterSet):
    location = django_filters.ModelMultipleChoiceFilter(
        queryset=Brand_Size_Location.objects.all(),
        name='brand_size__brand_size_location__location'
    )
    location_name = django_filters.CharFilter(
        name='brand_size__brand_size_location__location__name'
    )

class Meta:
    model = Brand
    fields = [
        'location',
        'location_name'
    ]

class BrandList(LoginRequiredMixin, generics.ListCreateAPIView): model = Brand serializer_class = BrandSerializer filter_class = BrandFilter

You can then use query parameters to filter on the URL like:

http://somehost/api/brands/?location=42

which uses a PK to filter, or with the location name (assuming you have a name field in the Location model):

http://somehost/api/brands/?location_name=Atlantis
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top