Home > Blockchain >  Getting Error while trying to get the value of the many to many field in django
Getting Error while trying to get the value of the many to many field in django

Time:04-22

models.py

class Organisation(models.Model):
    """
    Organisation model
    """
    org_id = models.AutoField(unique=True, primary_key=True)
    org_name = models.CharField(max_length=100)
    org_code = models.CharField(max_length=20)
    org_mail_id = models.EmailField(max_length=100)
    org_phone_number = models.CharField(max_length=20)
    org_address = models.JSONField(max_length=500, null=True)
    product = models.ManyToManyField(Product, related_name='products')
    org_logo = models.ImageField(upload_to='org_logo/')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "organisation_master"

    def __str__(self):
        return self.org_name

serializers.py

class Organisation_Serializers(serializers.ModelSerializer):
    product_name = serializers.CharField(source='product.product_name')
    class Meta:
        model = Organisation
        fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product','product_name')

While i tried to get the value of the product name iam getting an error as "Got AttributeError when attempting to get a value for field product_name on serializer Organisation_Serializers. The serializer field might be named incorrectly and not match any attribute or key on the Organisation instance. Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'.

Can you please help me to fix this issue.Posting the traceback error.

Request Method: GET
Request URL:    http://127.0.0.1:8000/api/onboarding/organisation/
Django Version: 3.2.12
Exception Type: AttributeError
Exception Value:    
Got AttributeError when attempting to get a value for field `product_name` on serializer `Organisation_Serializers`.
The serializer field might be named incorrectly and not match any attribute or key on the `Organisation` instance.
Original exception text was: 'ManyRelatedManager' object has no attribute 'product_name'.
Exception Location: C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py, line 490, in get_attribute
Python Executable:  C:\Users\gobs4\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.4
Python Path:    
['F:\\icaniotimesheet\\microservices',
 'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
 'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
 'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib',
 'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310',
 'C:\\Users\\gobs4\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time:    Thu, 21 Apr 2022 03:28:46  0000
Traceback Switch to copy-and-paste view
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py, line 457, in get_attribute
            return get_attribute(instance, self.source_attrs) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\fields.py, line 97, in get_attribute
                instance = getattr(instance, attr) …
▶ Local vars
During handling of the above exception ('ManyRelatedManager' object has no attribute 'product_name'), another exception occurred:
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
                response = get_response(request) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
        return view_func(*args, **kwargs) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\viewsets.py, line 125, in view
            return self.dispatch(request, *args, **kwargs) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 509, in dispatch
            response = self.handle_exception(exc) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 469, in handle_exception
            self.raise_uncaught_exception(exc) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 480, in raise_uncaught_exception
        raise exc …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 506, in dispatch
            response = handler(request, *args, **kwargs) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\mixins.py, line 46, in list
        return Response(serializer.data) …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py, line 768, in data
        ret = super().data …
▶ Local vars
C:\Users\gobs4\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\serializers.py, line 253, in data
                self._data = self.to_representation(self.instance) 

CodePudding user response:

the many-to-many field cannot be serialized to charfield

product_name = serializers.CharField(source='product.product_name')

insead try the solution below Django rest framework serializing many to many field

CodePudding user response:

First, create the Product Serializer in: ProductSerializer(serializers.Serializer): product = serializers.CharField(max_length=100)

class Organisation_Serializers(serializers.ModelSerializer):
product_name =  ProductSerializer(many=True)
class Meta:
    model = Organisation
    fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product','product_name')
  • Related