Home > Mobile >  How to fix getting None value on serializing ManyToManyField in django rest framework
How to fix getting None value on serializing ManyToManyField in django rest framework

Time:03-19

Sorry to ask a repetitive question which is already have been asked a lot of times. I have seen alot of answers on this topic. But I can't reproduce the solution of my problem. Basically I want to serialize a field name partner which is in quote model

class Quote(models.Model):
     #...
     partner = models.ManyToManyField(
        Partner, blank=True, related_name='quote_partners')

and this is the Partner models in the accounts app

class Partner(models.Model):
    id = models.UUIDField(primary_key=True,
                          unique=True,
                          default=uuid.uuid4,
                          editable=False)
    name = models.CharField(max_length=100, blank=True, null=True)
    group = models.OneToOneField(
        Group, on_delete=models.DO_NOTHING, blank=True, null=True)

    def __str__(self):
        return self.name

And this is how the serializer looks

class QuoteListSerializer(serializers.Serializer):
    """ For the List views """
    #...
    id = serializers.UUIDField(read_only=True)
    partner = serializers.CharField(read_only=True)

I'm getting all other fields properly but not the partner field. This is the end results looks like :

{           
            "id": "cbf64980-1637-4d0d-ad1f-4eb6421df5a1",
            "partner": "accounts.Partner.None", 
        },

However I can see the partners field is filled for this specific entry in the admin page but not showing in the serialized data. In the Partner Model

enter image description here

In the Quote

[enter image description here][2

Anybody knows why this is happening and how to fix this issue.

CodePudding user response:

If you already have the individual objects of the related fields, and as you mentioned in the comments you want the UUID which is a primary key of the Partner model as well, So can use the PrimaryKeyRelatedField.

PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. More Info

Modify your QuoteListSerializer from

partner = serializers.CharField(read_only=True)

to

partner = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

This will return the set of UUID of those specific objects that are linked to your Quote model.

"partner": [
                "115f1fa8-1cb2-4d49-962d-8c25e8b40240" # UUID of the linked partner
            ],

If you want to return the string value then u should use StringRelatedField

StringRelatedField may be used to represent the target of the relationship using its __str__ method. More Info,

This will return the name of the Partner Objects as you have set this in the Partner model to return self.name

So you can obtain as the following formate,

"partner": [
                "Company A" # name of the linked partner
            ],

CodePudding user response:

You have to make also a serializer class of the Partner class. In the QuoteListSerializer you call this partner serializer.The partner serializer will then be nested in the json.

class QuoteSerializer(serializers.ModelSerializer):

    partner = PartnerSerializer(read_only=True)

    class Meta:
        model = Quote
        fields = __All__ you can exclude fields
  • Related