0

I have the model specification below. MailingList is a reference table/model between Customer and Email. It has several other attributes, that will be useful in applying filters. My goal is to apply some filters then return serialized results. The results should include the customer's orders.

models.py

class Email(models.Model):
    name = models.CharField(max_length=300, unique=True)

class Item(models.Model):
    name = models.CharField(max_length=50)

class Customer(models.Model):
    passport_number = models.CharField(max_length=20, unique=True)
    name = models.CharField(max_length=20)

class Order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)

class MailingList(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    email = models.ForeignKey(Email, on_delete=models.CASCADE)

serializer.py

class CustomerSerializer(serializers.ModelSerializer):
    passport = serializers.CharField(source='customer.passport_number')
    customer_name = serializers.CharField(source='customer.name')

    # I want to add the orders for each customer too

    class Meta:
        model = MailingList
        fields = ['passport', 'customer_name']

views.py

class CustomerViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = MailingList.objects.filter(some_filters).prefetch_related('customer')

        serializer = CustomerSerializer(queryset, many=True)
        return serializer.data

Here's the response I'm currently getting

[
    {passport: 48, name: "Collins"},
    {passport: 32, name: "Kate"}
]

And here's the response I'm trying to get

[
    {passport: 48, name: "Collins", orders: {"1": "Hp EliteDisplay", "2": "Sony a7iii"}},
    {passport: 32, name: "Kate" orders: {}}
]

QUESTION: How do I embed orders within the same response?

The Voyager
  • 617
  • 9
  • 17
  • Does this answer your question? [LEFT JOIN Django ORM](https://stackoverflow.com/questions/21271835/left-join-django-orm) – Alireza Jul 31 '21 at 18:05
  • No. I Actually saw this while searching for a solution. My case is different, details are in the question and code samples – The Voyager Jul 31 '21 at 18:28

1 Answers1

0

Use https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

class CustomerSerializer(serializers.ModelSerializer):
    passport = serializers.CharField(source='customer.passport_number')
    customer_name = serializers.CharField(source='customer.name')
    orders = serializers.SerializerMethodField()

    def get_orders(self, mailing_list):
      return OrderSerializer(queryset=mailing_list.customer.order_set.all(), many=True)

    # I want to add the orders for each customer too

    class Meta:
        model = MailingList
        fields = ['passport', 'customer_name', 'orders']
Bindeep
  • 31
  • 4