Django Serializer's Source argument is not working

Viewed 199

I am trying to get all the bills and their customer-related details (i.e. 'customer_code', 'email' etc.) with it.

However, source='user.customer_code does not seem to have any effect at all. What am I missing?

I have been following along this:

this stackoverflow post with no luck.

My two models:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(db_index=True, unique=True, max_length=200)
    customer_code = models.CharField(max_length=300, blank=True, null=True, default=None)
class Bill(models.Model):
    customer = models.ForeignKey(
        User, on_delete=models.CASCADE, blank=True, null=True, related_name="customer_bill"
    )
    payable_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0)

View:

class BillView(APIView):
    def get(self, request, format=None):
        q = Bill.objects.all().select_related('customer')        
        s = BillSerializer(q, many=True)
        return JsonResponse({            
            "bill": s.data
        })

Serializer:

class BillSerializer(serializers.ModelSerializer):
    
    customer_code = serializers.CharField(source='user.customer_code', read_only=True)
    
    class Meta:
        model = Bill        
        fields = ('id','payable_amount','customer_code') # binding customer_code here 

Current Output:

"bill": [
        {
            "id": 1,
            "payable_amount": "1000.00"
        },
        {
            "id": 2,
            "payable_amount": "2000.00"
        }
    ]

Expected Result:

"bill": [
        {
            "id": 1,
            "payable_amount": "1000.00",
            "customer_code": "CUS10001"   # want this to be attached

        },
        {
            "id": 2,
            "payable_amount": "2000.00",
            "customer_code": "CUS10002"   # want this to be attached
        }
    ]
0 Answers
Related