Search code examples
djangorestful-url

Django Restful Api of ManytoMany models to show the foreign objects


The "Brand" object is foreign key of "company",they are ManytoMany relationship,and Brand object exists the field "company_Group"

the models are as follows:

class Brand(models.Model):
      Company_Group = models.ManyToManyField(Company)
      Brand_Group = models.CharField(u'Brand Group',max_length=255, default="")
      Pref_Brand_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="")
      Pref_Brand_Name = models.CharField(u'Preferred Name',max_length=255, default="")
      PrimaryContact = models.ForeignKey(UserRole, null=True, blank=True) 



class Company(models.Model):
      Pref_Company_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="")
      Pref_Company_Name = models.CharField(u'Preferred Name',max_length=255, default="")
      Company_Type = models.CharField(u'Company Type',max_length=255, default="")

serializers

class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'

the Serializer as follows ,data_export_setting.Company_form_stand is the field as

class CompanySerializer(serializers.HyperlinkedModelSerializer):
    Brand = BrandSerializer(source='brand', read_only=True)
    class Meta:
        model = Company
        Company_form_stand=['id', 'Brand', 'Company_Type','Company_Name','company_Name_SC']
        fields = data_export_setting.Company_form_stand
        depth = 2

    def create(self, validated_data):
        return Company.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.__dict__.update(**validated_data)
        instance.save()
        return instance

the viewset are as follows

class BrandViewSet(viewsets.ModelViewSet):
     queryset = Brand.objects.all()
     serializer_class = BrandSerializer
     model = Brand

     def get_serializer(self, *args, **kwargs):
         if 'data' in kwargs:
             data = kwargs['data']
             if isinstance(data, list):
                 kwargs['many'] = True
    return super(BrandViewSet, self).get_serializer(*args, **kwargs)


class CompanyViewSet(viewsets.ModelViewSet):
      queryset = Company.objects.all()
      serializer_class = CompanySerializer

and I want to show the company objects with Brand objects ,however,it seems to ignore the brand object and its field

the field ignore the company!

appreciate any help ,thanks


Solution

  • Try,

    Brand = BrandSerializer(source='brand_set', read_only=True, many=True)
    

    Since, you have defined the field relation as ManyToMany, more than one Brand objects are related to a single Company instance. By using the reverse relation, you can access them in your serializer, and many=True lets the serializer handle multiple objects in the relation.