27377

Reformat Django REST Framework Serializer to get Output

<h3>Question</h3>

I am trying to get data in a particular format but i'm not able to get the desired output.

My Model:

class Category(models.Model): name = models.CharField(max_length=40) class Expense(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") description = models.CharField(max_length=200) total_amount = models.IntegerField() class Expense_Details(models.Model): expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name="payment") user = models.IntegerField() amount = models.FloatField() type = models.CharField(max_length=100) ---->type is owe or lend

When I request /api/expenses/:

Expected Output { “total_expenses”: 10, “Expenses”: [{ “id”: 1, “category”: 1, “created_by”: 1, ------> user logged id “description”: “lunch”, “total_amount”: “105”, “owe”: [{ “user_id”: 1, “amount”: 10 }, { “user_id”: 2, “amount”: 95 }], “lend”: [{ “user_id”: 3, “amount”: 10 }, { “user_id”: 4, “amount”: 95 }], }, ... ] }

My output:

{ "results": [ { "id": 1, "category": 1, "description": "lunch at the burj al arab", "total_amount": 105, "payment": [ { "user": 1, "amount": -10 }, { "user": 2, "amount": -95 }, { "user": 3, "amount": 10 }, { "user": 4, "amount": 95 } ] } ] }

My Serializer:

class ExpenseDetailsSerializer(serializers.ModelSerializer): class Meta: model = Expense_Details fields = ['user', 'amount'] class ExpenseSerializer(serializers.ModelSerializer): payment = serializers.SerializerMethodField() def get_payment(self, obj): return ExpenseDetailsSerializer(obj.payment.all(), many=True).data class Meta: model = Expense fields = ['id', 'category', 'description', 'total_amount', 'payment',]

What Query should I use to get Output in the above format? How will my serializer look like? How can I separate own and lend? Also I have stored own and lend with + and - sign to differentiate between them.


<h3>Answer1:</h3>

Use a ListField for the same.

Documentation: https://www.django-rest-framework.org/api-guide/fields/#listfield

Also refer How to serialize an 'object list' in Django REST Framework

Here you can try something like:

class ExpenseSerializer(serializers.Serializer): payment = serializers.ListField(child=ExpenseDetailsSerializer()) def get_payment(self, obj): return ExpenseDetailsSerializer(obj.payment.all(), many=True).data class Meta: model = Expense fields = ['id', 'category', 'description', 'total_amount', 'payment',]

来源:https://stackoverflow.com/questions/61929711/reformat-django-rest-framework-serializer-to-get-output

Recommend

  • Finding an odd number from int[] array using Stream
  • Long press event on button [duplicate]
  • jQuery datepicker restrict months
  • Generate Local Notification For every 28 days iOS 10 Objective-C
  • Setting up Wordpress and Flask on Apache2
  • Why context.Wait in StartAsync didn't stop the dialog
  • Is there way to structure a QueryExpression so that you could dynamically handle a unknown number of
  • Button On Click event not firing
  • Store token for FCM
  • Running iPhone crash Logs from testers on XCode
  • view details for exception in vs 2017
  • how to add dashed border on highcharts “area” graph for every point
  • Copy and paste data from multiple workbooks to a worksheet in another Workbook
  • 'Edit' function for forum posts and such
  • Reload Page with Javascript after Database changes
  • trigger ontouch event programmatically
  • Annotate objects in a queryset with next and previous object ids
  • How to merge objects within array based on attribute
  • Typeahead.js does give me suggestions but doesn't select them
  • PHPMailer return to AJAX
  • How convert html to BBcode in C#
  • Unable to create Access token grant type in wso2 API manager store to test API
  • Print Longitude and Latitude in textbox Android
  • How to use Streams api peek() function and make it work?
  • iphone image to video issue in video speed
  • How to decleare char *const argv[] in swift [duplicate]
  • How to get rgb from transparent pixel in js
  • Computing the discrete fourier transform of audio data with FFTW
  • Using Service Component Runtime
  • WPF custom control and direct content support
  • PHP Permalinks.. how to change?
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • Access to a Matlab gui from the web
  • convert json to excel in java
  • Create/delete users from text file using Bash script