简体   繁体   中英

How to retrieve a many-to-many field with backward relationships lookup in Django REST Framework serializer?

Please correct my title if it's not correct. My problem is I want to retrieve FinishType 's name from Product . I have tried 2 ways to achieve this: first attempt and second attempt .
My simplifed related models in models.py :

class Product(models.Model):
    product_id = models.CharField(max_length=6)
    color = models.ForeignKey(ColorParent, on_delete=models.SET_NULL, null=True)
    collection = models.ForeignKey(ProductCollection, on_delete=models.SET_NULL, null=True)

    @property
    def get_distributors(self):
        return Distributor.objects.filter(distributor__products=self).count()

    def __str__(self):
        return self.product_id

class FinishType(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

class ProductFinishType(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    market = models.ForeignKey(Market, on_delete=models.CASCADE)
    finish_types = models.ManyToManyField(FinishType)

    def __str__(self):
        return '%s - %s' % (self.product, self.market)

class ProductAlias(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    market = models.ForeignKey(Market, on_delete=models.CASCADE)
    name = models.CharField(max_length=50, null=True, blank=True)

    def __str__(self):
        return '%s - %s' % (self.product, self.name)

My serializers.py :

class ProductGridSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField(source='get_name')
    finishing = serializers.SerializerMethodField('get_finish_types')
    distributor = serializers.ReadOnlyField(source='get_distributors')

    @staticmethod
    def get_name(obj):
        return [pa.name for pa in obj.productalias_set.all()]

    @staticmethod
    def get_finish_types(obj):
        return [pft.name for pft in obj.productfinishtype_set.all().select_related('finish_types')]  # first attempt

    class Meta:
        model = Product
        fields = ['id', 'product_id', 'name', 'collection', 'finishing', 'distributor']

First attempt works for name field which fetches ProductAlias 's name but gives me this error:

FieldError at /api/product_grids/
Invalid field name(s) given in select_related: 'finish_types'. Choices are: product, market

My get_finish_types() on second attempt:

@staticmethod
def get_finish_types(obj):
    product_finish_types = obj.productfinishtype_set.all()
    response = ProductFinishTypeSerializer(product_finish_types, many=True, source='finish_types').data
    return response

It gives me the whole object datas:

{
      "id": 1,
      "product_id": "BQ1111",
      "name": [
            "White Stone"
      ],
      "collection": 1,
      "finishing": [
          {
              "id": 1,
              "product": 1,
              "market": 1,
              "finish_types": [
                  1,
                  3,
                  5
              ]
          }
      ],
      "distributor": 5
},

My desired output is something like:

{
      "id": 1,
      "product_id": "BQ1111",
      "name": [
            "White Stone"
      ],
      "collection": 1,
      "finishing": [
            "Polished",
            "Carved",
            "Melted"
      ],
      "distributor": 5
},

Create a serializer for FinishType ,

class FinishTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = FinishType
        fields = ('name',)

and wire-up it in ProductGridSerializer using SerializerMethodField

class ProductGridSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField(source='get_name')    
    distributor = serializers.ReadOnlyField(source='get_distributors')
    

    @staticmethod
    def get_name(obj):
        return [pa.name for pa in obj.productalias_set.all()]

    class Meta:
        model = Product
        fields = ['id', 'product_id', 'name', 'collection', 'finishing', 'distributor']

Inspired by @Arakkal Abu's queryset, I tried it using my first attempt.
FinishTypeSerializer added in serializers.py :

class FinishTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = FinishType
        fields = ('name',)

ProductGridSerializer in serializers.py :

class ProductGridSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField(source='get_name')
    finishing = serializers.SerializerMethodField(source='get_finishing')
    distributor = serializers.ReadOnlyField(source='get_distributors')

    @staticmethod
    def get_name(obj):
        return [pa.name for pa in obj.productalias_set.all()]

    @staticmethod
    def get_finishing(product):
        return [pft.name for pft in FinishType.objects.filter(productfinishtype__product=product)]

    class Meta:
        model = Product
        fields = ['id', 'product_id', 'name', 'collection', 'finishing', 'distributor']

The JSON output is:

{
     "id": 1,
     "product_id": "BQ1111",
     "name": [
           "White Stone"
     ],
     "collection": 1,
     "finishing": [
           "Polished",
           "Honed",
           "Carved"
     ],
     "distributor": 5
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM